Home > Enterprise >  Why isn't the derived class destructor being called?
Why isn't the derived class destructor being called?

Time:03-08

I was doing some practicing with pointers to derived classes and when I ran the code provided underneath,the output I get is

Constructor A
Constructor B
Destructor A

Could someone tell me why is B::~B() not getting invoked here?

class A {
 public:
  A() { std::cout << "Constructor A\n"; }
  ~A() { std::cout << "Destructor A\n"; }
};

class B : public A {
 public:
  B() { std::cout << "Constructor B\n"; }
  ~B() { std::cout << "Destructor B\n"; }
};

int main() {
  A* a = new B;
  delete a;
}

CodePudding user response:

The static type of the pointer a is A *.

A* a = new B;

So all called member functions using this pointer are searched in the class A.

To call the destructor of the dynamic type of the pointer, that is of the class B, you need to declare the destructor as virtual in class A. For example:

#include <iostream>

class A {
 public:
  A() { std::cout << "Constructor A\n"; }
  virtual ~A() { std::cout << "Destructor A\n"; }
};

class B : public A {
 public:
  B() { std::cout << "Constructor B\n"; }
  ~B() override { std::cout << "Destructor B\n"; }
};

int main() {
  A* a = new B;
  delete a;
}

CodePudding user response:

becuase overriden methods need to be virtual

class A{
public:
    A()
    {
        std::cout<<"Constructor A\n";
    }
    virtual ~A()
    {
        std::cout<<"Destructor A\n";
    }
};
class B : public A{
public:
    B()
    {
        std::cout<<"Constructor B\n";
    }
    virtual ~B()
    {
        std::cout<<"Destructor B\n";
    }
};
  • Related