Mahesh Bhandari
Mahesh Bhandari

Reputation: 11

Omitting keyword virtual before destructor still works virtually

#include<iostream>
using namespace std;

class Mahesh
{

   public:
      Mahesh(){
         cout<<"Base Constructor is called at here"<<endl<<endl;
      }
      virtual ~ Mahesh()
      {
         cout<<"Base Destructor is called"<<endl<<endl;
      }
};

class Purnima:public Mahesh
{

   public:

      Purnima()
      {
         cout<<"Derived class constructor"<<endl<<endl;
      }
      ~Purnima(){
         cout<<"Derived class Destructor"<<endl<<endl;
      }
};

int main()
{
   Mahesh *m1;
   Purnima p1;
   m1=&p1;

   return 0;
}

My question is if I don't write keyword virtual in front of destructor then above code works fine, then why virtual destructor?

Upvotes: 1

Views: 79

Answers (2)

Pete Becker
Pete Becker

Reputation: 76245

Nothing in this code requires a virtual destructor, so it does, indeed, work fine. You need a virtual destructor if you delete an object of a derived type through a pointer to the base type. Like this:

Mahesh *m1 = new Purnima;
delete m1;

If the destructor of Mahesh is not virtual, this code has undefined behavior. Beware: one of the most insidious manifestations of undefined behavior is that the code "works fine", until you make a slight change somewhere else, in preparation for a demo to your most important client, at which point it will fail disastrously.

Upvotes: 1

Daksh Gupta
Daksh Gupta

Reputation: 7804

When you write the code like this

int main()
{
   Mahesh *m1;
   Purnima p1;
   m1=&p1;

   return 0;
}

You get Purnima p1 destructed automatically when you get out of scope.. that's why you get appropriate destructor sequence call.

Anyway you can't delete the m1 otherwise its a crash.

Try enclosing inside the scope to understand it better.

int main()
{
   {
     Mahesh *m1;
     Purnima p1;
     m1=&p1;
   }
   cout<<"After Scope.."<<endl;

   return 0;
}

"After Scope" shall be printed after destructor call.

So in a nutshell, you need virtual when dealing with dynamic types

Upvotes: 0

Related Questions