msc
msc

Reputation: 34578

Allocate memory of Base class pointer using derived class

I'm newbie in C++. I'm learning c++ oops concepts. Is it allowed to using Derived class(D) allocate the memory of Base class(B) pointer?

B *a = new D();

My code:

#include <iostream>
using namespace std;

class B
{
public:
        B()
        {
                cout<<"B constructor"<<endl;
        }

        ~B()
        {
                cout<<"B Destroctur"<<endl;
        }
};

class D : public B
{
public:
        D()
        {
                cout<<"D constructor"<<endl;
        }

        ~D()
        {
                cout<<"D Destroctur"<<endl;
        }
};

int main()
{
        B *a = new D();
        delete a; // Is valid?
}

Also, Is it valid to free the memory of base class pointer?

delete a;

Upvotes: 2

Views: 1624

Answers (3)

Eswaran Pandi
Eswaran Pandi

Reputation: 670

As per your code, the output will be

B constructor
D constructor
B Destructor  ==> Base class 

Derived class memory will not deleted. So avoid that, we need to use virtual keyword in base class destructor.

virtual ~B()
{
     cout<<"B Destroctur"<<endl;
}

during run time, while calling base class (B) destructor, it calls derived class destructor (D) and then base class destructor executed.

if base class destructor is virtual, the output will be

B constructor
D constructor
D Destructor  ==> Derived class
B Destructor  ==> Base class

Upvotes: 1

Anže
Anže

Reputation: 181

What you did was created and object of class D which is derived from class B. Pointer of type B that the address of created object is assigned to is a pointer with instruction to point to "B part of class D". The object created is still of class D and can be cast into class D pointer.

This is also a way to restrict usage of D class functionalities in a current scope or create a list of objects with different types which must all be derived from the same base class (typical example is dog and cat class extend animal class and are both put in pets<animal> list)

Upvotes: 1

Andrew Kashpur
Andrew Kashpur

Reputation: 746

it is valid as long as you declare base destructor virtual:

virtual ~B() { /*B destructot code*/}

Upvotes: 4

Related Questions