2

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;
msc
  • 30,333
  • 19
  • 96
  • 184

3 Answers3

4

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

virtual ~B() { /*B destructot code*/}
Andrew Kashpur
  • 706
  • 5
  • 13
  • 1
    Why you need base d'tor as `virtual`, see [here](http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – sameerkn Feb 09 '17 at 12:04
1

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)

Anže
  • 181
  • 8
1

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
Eswaran Pandi
  • 318
  • 2
  • 10