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.

Note: Constructors are never virtual, Destructors  are virtual.


Example Without virtual


#include <iostream>
using namespace std;

class Base
{
    public:
       Base(){ cout<<"Constructing Base";}
      
     // this is a destructor:

 ~Base(){ cout<<"Destroying Base";}
};

class Derive: public Base
{
        public:
        Derive(){ cout<<"Constructing Derive";}
       
        ~Derive(){ cout<<"Destroying Derive";}
 };

void main()
{
     Base *basePtr = new Derive();
        
        delete basePtr;
}

Output after running code

Constructing Base  
Constructing Derive 
Destroying Base

Example With virtual

class Base
{
    public:
         Base(){ cout<<"Constructing Base";}

    // this is a virtual destructor:
    virtual ~Base(){ cout<<"Destroying Base";}
};
class Derive: public Base
{
        public:
        Derive(){ cout<<"Constructing Derive";}
       
        ~Derive(){ cout<<"Destroying Derive";}
 };

void main()
{
     Base *basePtr = new Derive();
        
        delete basePtr;
}

Output after running code
Constructing Base  
Constructing Derive 
Destroying Derive
Destroying Base


Posted by Unknown On 23:57 No comments

0 comments:

Post a Comment

  • RSS
  • Delicious
  • Digg
  • Facebook
  • Twitter
  • Linkedin
  • Youtube

Blog Archive

Contact Us


Name

E-mail *

Message *