Start New Discussion within our Software Development Community

In the following code:

#include <iostream.h>
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;}
> };
void main()
{
        Base *Var = new Derived();
        delete Var;
}

why is constructor of Base is also being called when only the constructor is Derived being called by new? Why is the calling of the constructor of Derived is called? And also why the destructor of Derived is not called at all?

>why is constructor of Base is also being called
Because the Base part of the Derived object still needs to be constructed. This is done with the Base constructor. Think of it as an implicit call to the Base constructor:

Derived(): Base() { cout<<"Constructor: Derived"<<endl;}

>Why is the calling of the constructor of Derived is called?
Um, because you explicitly asked for it? In new Derived() , Derived() is basically a constructor invocation.

>And also why the destructor of Derived is not called at all?
Because you didn't make your destructors virtual, and the destruction is being done through a pointer to Base. Unless the destructors are virtual, there's no good way for the compiler to know that the object being pointed to is a derived class object. This is a classic polymorphism error in C++.

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