-1

I have a base class and a derived class, like:

class Base {
  virtual ~Base();
};
class Derived {
  ~Derived() {
    // for some reason, i need base's deconstructor called before derived's
  }
}

the normal call order of deconstructor is : ~Derived(); ~Base();

but for some reason, i need to call ~Base() first, how can i do this?

nick
  • 832
  • 3
  • 12
  • Does this answer your question? [Do I need to explicitly call the base virtual destructor?](https://stackoverflow.com/questions/677620/do-i-need-to-explicitly-call-the-base-virtual-destructor) – Allan Wind Mar 17 '21 at 04:34
  • 3
    You cannot, at least not without running into undefined behavior in this scneario. Most likely you don't need to, either. You should post the real problem you are trying to solve, since this is not the right solution. – dxiv Mar 17 '21 at 04:36
  • @dxiv I am sorry, please see the new descrption – nick Mar 17 '21 at 04:40
  • @nick Now after the edit, the title is the opposite of what you are asking in the body of the question. Either way, no, you can't call the Base destructor explicitly here, because the whole object becomes invalid after the destructor is executed. – dxiv Mar 17 '21 at 04:41
  • Maybe you want a `Base::clear()` method. – Jarod42 Mar 17 '21 at 09:00

1 Answers1

2

You can't. Deconstructors are called in reverse order of construction automatically by the compiler.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
  • if i do need to call base class's deconstructor first, there's no way can do this? – nick Mar 17 '21 at 04:38
  • Correct, you have no control of the behavior. If you call the constructor explicitly, it will run again and probably cause a segmentation fault. – Allan Wind Mar 17 '21 at 04:39