585

XYZ

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class X
  6. {
  7. public:
  8.     X() { p = new int[ 2 ]; cout << "X()\t"; }
  9.     void f( ) { cout << "X::f()\n"; }
  10. #if 0
  11.     ~X() { delete [] p; cout << "~X()\n"; } // memory leak
  12. #else
  13.     virtual ~X() { delete [] p; cout << "~X()\n"; }
  14. #endif
  15. private:
  16.     int *p;
  17. public:
  18.     int a;
  19. };
  20.  
  21. class Y : public X
  22. {
  23. public:
  24.     Y() { q = new int[ 1022 ]; cout << "Y(): Y::q = " << q << "\t"; }
  25.     ~Y() { delete [] q; cout << "~Y() "; }
  26.     void f( ) { cout << "Y::f()\n"; }
  27. private:
  28.     int *q;
  29. public:
  30.     int a;  // overrides X::a
  31. };
  32.  
  33. int main() {
  34.     for ( int i = 0; i < 8; i++ )
  35.     {
  36.         X *x = new Y;
  37.         delete x;
  38.     }
  39.     X x;
  40.     x.a = 22;
  41.     cout << endl;
  42.     x.f();
  43.     cout << "x.a = " << x.a << endl;
  44.     Y y;
  45.     y.a = 44;
  46.     y.X::a = 66;
  47.     cout << endl;
  48.     y.f();
  49.     y.X::f();
  50.     cout << "y.a = " << y.a << endl;
  51.     cout << "y.X::a = " << y.X::a << endl;
  52.     X z = y;
  53.     cout << "z.a = " << z.a << endl;
  54. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].