-1

I understand that if we want to call the Destructor of our derived object which has been assigned to a pointer to base we want to make the base destructor as virtual. However if we had something like this:

#include <iostream>
using namespace std;
class base
{

public:
base() { cout << "Base Constructor Called\n"; }
virtual ~base() { cout << "Base Destructor called\n"; }

};
class derived1 :public base
{

public:
derived1() { cout << "Derived1 constructor called\n"; }
~derived1() { cout << "Derived1 destructor called\n"; }

 };

 class derived2 : public derived1
 {
public:
derived2() { cout << "Derived2 constructor called\n"; }
~derived2() { cout << "Derived2 destructor called\n"; }

  };

class derived3 : public derived2
{
  public:
derived3() { cout << "Derived3 constructor called\n"; }
~derived3() { cout << "Derived3 destructor called\n"; }

 };

and we have the main function like this:

int main (){
base* ptr=new derived3;
delete ptr;

and the output is:
Base Constructor Called Derived1 constructor called Derived2 constructor called Derived3 constructor called Derived3 destructor called Derived2 destructor called Derived1 destructor called Base Destructor called

this calls base,derived1,derived2,and derived3 destructors which works just fine. we only made the base destructor as virtual.
why it is not necessary to make derived1,and derived2 destructors as virtual to produce the same results?

  • 3
    I [posted this answer](http://stackoverflow.com/a/36760987/440558) just a couple of hours ago, with quotes from the C++ specification that says why it's not needed for the child-classes. The last quote is the one you should read. It's the same with *all* member functions by the way, if a base class declares it as virtual, then it's virtual in all child classes too. – Some programmer dude Apr 21 '16 at 08:50

2 Answers2

2

All classes derived from a class with a virtual destructor have virtual destructors implicitly.

This applies to any member function in your class hierarchy.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
2

Once you declare a function as virtual, it implicitly remains virtual in all of the derived classes.

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • Doesn't that only hold true for the destructor? – Rotem Apr 21 '16 at 08:48
  • Interesting, I don't know why I assumed that omitting `virtual` on an overridden method in a derived class would seal the method. – Rotem Apr 21 '16 at 08:54
  • 1
    @Rotem you can still seal a method with the `final` keyword. – Quentin Apr 21 '16 at 08:55
  • A bit opinionated and off-topic, but would you say it is still considered good practice to mark virtual methods as such in headers of derived classes? – Rotem Apr 21 '16 at 08:57
  • 1
    @Rotem no. The preferred method is to mark them with `override`, which implies `virtual` *and* ensures that overriding has been properly done (e.g. against error in parameter types that would create a new, unrelated function). – Quentin Apr 21 '16 at 08:59