Monday, October 24, 2011

Why we need virtirtual destructor?

When you release the resource of an class object, usually you leverage the object's destructor. Assume we have two class here: base Class A and derived Class B, for the following code:
class A{
  public:
    ~A(){}
};

class B: public A{
   public:
    ~B(){}
};

B *b = new B();
delete b;
First B's destructor will be called, followed by A's. On the other side, if we have the following code:
class A{
  public:
    ~A(){}
};

class B: public A{
   public:
    ~B(){}
};

A *a = new B();
delete a;
Only A's destructor will be called. In order to also call B's destructor in the second code example, the ~A() should be declared as virtual.

No comments:

Post a Comment