Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ Inheritance, Derived class destructor not called when pointer object to base class is pointed to derived class

I am a newbie and I know this is a very basic concept and might be a duplicate too. Is it not true that once a constructor is called its corresponding destructor has to be called? [code run on Dev C++]

class Base
    {
     public:
            Base() { cout<<"Base Constructor\n";}
            int b;
     ~Base() {cout << "Base Destructor\n"; }
    };

class Derived:public Base
{
 public:
        Derived() { cout<<"Derived Constructor\n";}
        int a;
 ~Derived() { cout<< "Derived Destructor\n"; }
}; 
int main () {
Base* b = new Derived;    
//Derived *b = new Derived;
 delete b;
    getch();
    return 0;
}

GIVES OUTPUT

Base Constructor
Derived Constructor
Base Destructor
like image 721
Raghu Avatar asked Aug 09 '14 15:08

Raghu


People also ask

Does derived class inherit destructor?

Derived classes do not inherit or overload constructors or destructors from their base classes, but they do call the constructor and destructor of base classes. Destructors can be declared with the keyword virtual .

Does derived destructor call base destructor?

A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.

What happens when a base class pointer points to a derived class object?

Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.

How destructors are called during inheritance?

Destructors are called automatically when a variable goes out of scope. Because the base class destructor is inherited, and because the derived class object "is" a base class object, both the derived class destructor (even if it is the "default" destructor) and the base class destructor are called automatically.


1 Answers

Your code has undefined behavior. The base class's destructor must be virtual for the following to have defined behavior.

Base* b = new Derived;    
delete b;

From the C++ standard:

5.3.5 Delete

3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

So in your case, the static type is Base, and the dynamic type is Derived. So the Base's destructor should be:

virtual ~Base() {cout << "Base Destructor\n"; }
like image 110
PaulMcKenzie Avatar answered Sep 29 '22 01:09

PaulMcKenzie