Search code examples
c++virtual-destructor

Default destructor in subclasses of base class with a virtual destructor


I have a base class A with a virtual destructor. A has descendants B and C which use the default destructor. Is it safe to delete an object of C through a pointer to A?

More specifically, consider this sample code:

class A {
 public:
      A(){};
      virtual ~A() {/* code here */};
 };
 class B: public A {
      B() {/* code....*/};
      /* NO DESTRUCTOR SPECIFIED */
   };
 class C: public B {/*same as above, no destructor */};
 class D: public B {/* same as above, no destructor*/}

The code to be run looks something like this:

A* getAPointer(void); /* a function returning a C or a D*/
A* aptr=getAPointer();
/* aptr is declared as A*, but points to either an object of class C 
  or class D*/
delete aptr;

Is the delete aptr safe? Does it do the right thing: if aptr points to an object of class C, the aptr first calls C's destructor, then B's destructor, and finally A's destructor ?


Solution

  • Is it safe to delete an object of C through a pointer to A?

    Yes, it is totally safe as all the destructors in classes B, C and D will be implicitly virtual.

    From:

    15.4 Destructors [class.dtor]

    10 A destructor can be declared virtual (13.3) or pure virtual (13.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined. If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual.

    As A has a virtual destructor, then B, and C, D respectively, have virtual destructors and:

    delete aptr;
    

    works correctly.