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?