I have got an assignment question :
Constructors cannot be virtual , however destructors can. Justify the statement in reference to memory leak.

Please help me out figuring the answer.

Here is one explaination, but the examples are not good. Below is corrected example. Test it out on your own computer by comparing the outputs with and without the virtual keywords.

#include <iostream>
using namespace std;

class Base
{
       public:
          Base(){ cout<<"Constructor: Base"<<endl;}
          virtual ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
     //Doing a lot of jobs by extending the functionality
       public:
           Derived(){ cout<<"Constructor: Derived"<<endl;}
           virtual ~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
int main()
{
        Base *Var = new Derived();
        delete Var;
}

I still didn't understand the following ouput:

#include <iostream>
using namespace std;

class Base
{
       public:
      Base(){ cout<<"Constructor: Base"<<endl;}
          ~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
     //Doing a lot of jobs by extending the functionality
       public:
       Derived(){ cout<<"Constructor: Derived"<<endl;}
          ~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
int main()
{
        Base *Var = new Derived();
        delete Var;
		return 0;

}

The output of the above program is :
Base constructor
Derived constructor
Base Destructor

Why is the derived destructor not in the output. It does appear when using the keyword virtual both the destructors.

>>Why is the derived destructor not in the output. It does appear when using the keyword virtual both the destructors.

You got it! :) That's why we use virtual destructors. I think there is an explaination for that behavior in the link I posted.

This article has been dead for over six months. Start a new discussion instead.