0
#include <iostream>
class a{
  public:
    a(){};
    virtual ~a(){
      std::cout << "del class a";
    }
};

class b: public a{
  public:
    ~b(){
      std::cout << "del class b";
    } 
};

int main(){

    a *pa;
    pa = new b;
    delete pa;

}

Hi, I'm fairly new to C++. Looking at the code example above, class b does not have a virtual destructor, but when the program executes, the output is del class b then del class a.

I'm wondering why that's the case, as I have not created a virtual destructor in class b. Does that mean by declaring the base destructor virtual, the "virtualness" of the derived class is implicit? Thanks.

Roy
  • 63
  • 8
  • Does this answer your question? [Virtual destructor in polymorphic classes](https://stackoverflow.com/questions/29363817/virtual-destructor-in-polymorphic-classes) – NutCracker Feb 02 '20 at 09:31
  • Yes, "virtualness", not only in case of destructor, is implicitly derived. – W.F. Feb 02 '20 at 09:33
  • @NutCracker No, i was talking more on the lines of why calling a non virtual and derived destructor makes sense. But thanks for resource anyway! – Roy Feb 02 '20 at 09:45

1 Answers1

1

Even though destructors are not inherited, if a base class declares its destructor virtual, the derived destructor always overrides it. This makes it possible to delete dynamically allocated objects of polymorphic type through pointers to base.

You can find more in Cppreference-Virtual destructor