top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

In C++, what’s a virtual destructor and when is it needed?

+2 votes
531 views
In C++, what’s a virtual destructor and when is it needed?
posted Jan 13, 2014 by Dheerendra Dwivedi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes

If the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.

Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor. We need virtual destructor when someone will delete a derived-class object via a base-class pointer.

For example

class a
{
           public:          
           a(){printf("\nBase Constructor\n");}
           ~a(){printf("\nBase Destructor\n");} 
};

class b : public a 
{
         public:
         b(){printf("\nDerived Constructor\n");}
         ~b(){printf("\nDerived Destructor\n");} 
};
int main()
{
         a* obj=new b;
         delete obj;
         return 0;
}

Output:

Base Constructor
Derived Constructor
Base Destructor

Now just by Changing

~a(){printf("\nBase Destructor\n");}
to
virtual ~a(){printf("\nBase Destructor\n");}

Output:

Base Constructor
Derived Constructor
Derived Destructor
Base Destructor 
answer Jan 13, 2014 by Dheeraj Shetty
...