Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling child method from parent destructor in C++

Tags:

c++

class A {
public:
  ~A() { release(); }
  virtual release() { cout << "~A"; } 
}

class B : public A {
  release() { cout << "~B"; }
}

When I delete B, only A class release() method is called.

What I want to achieve is for every child object, when it is deleted, I want to call release method which is overriden in each child class, without manually specifying destructor for each child with call to release (I'm lazy). Is this actually not possible to achieve in this or any other way?

like image 995
SMGhost Avatar asked Dec 11 '22 19:12

SMGhost


1 Answers

Destructors are executed in the reverse order of constructors, so when the A in a B is destroyed its B component has already been destroyed and no longer exists. Calling a method on a destroyed object yields undefined behavior, and that's why calls to virtual methods always resolve to the current class type within a constructor or destructor.

So basically no, you cannot do it. You will have to write them all.

like image 130
K-ballo Avatar answered Dec 21 '22 06:12

K-ballo