tags:

views:

85

answers:

2
class A { 
 public:
  A() { } 
  ~A() { cout << "A Destructor \n" ; } 
};

class B :public A{ 
   public:
   B() { } 
   virtual ~B() { cout << "B Destructor \n" ; } 
};

class C : public B {
   public:
   C() { }
   ~C() { cout << "C Destructor \n"; }
};

int main()
{

   A *pointA = new A;
   A *pointB = new B;
   A *pointC = new C;

   delete pointA;
   delete pointB;
   delete pointC;
}
+10  A: 

It will invoke undefined behavior at the second (and third) delete, because A's destructor is not virtual.

§5.3.5/3:

if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.


If you make the destructor of A virtual, you get well-defined behavior, and the destructor of the dynamic type is called. (And each of those in turn calls the base destructor.) Your output would be:

A destructor
B destructor
A destructor
C destructor
B destructor
A destructor


For what it's worth, when you're that close to a compilable snippet, you should leave the includes. Also, just use struct instead of class to be concise about the public stuff, and leave out empty constructors.

GMan
Thanks a lot Gman.
A: 

As GMan pointed out, attempting to call the delete operator on a base pointer requires a virtual destructor for the compiler to be able to destroy subclass objects correctly. A lot of people oversimplify this to a rule like, "If a class has virtual functions, it needs a virtual destructor." That is not necessarily the case; even a base class which has no virtual functions still needs a virtual destructor if you want to allow clients to delete the class through a base pointer. If you don't, the destructor should be protected and not public.

There is an excellent book that describes this in detail and more called C++ Coding Standards by Herb Sutter. I recommend it as a starting point in your C++ adventures. :-)