Search code examples
c++exceptionvirtual-destructor

exception with non virtual destructor c++


When we go out of catch block scope, does the exception destructor get called? (In case we don't rethrow it)

Suppose I have class A, and that its destructor is not virtual. B inherits A. Suppose some function threw object of B class as an exception, and it was caught by a catch block

catch(A& a){
...
}

If the exception destructor should be called when go out of catch scope, in this case only the base class A's destructor will be called?

Cornstalks: live trial result in calling both class destructor.

It contradicts my logic. Explain someone?


Solution

  • OK, someone already answered your first question. I'll focus on this one:

    if the exception destructor should be called when go out of catch scope, in this case only the base class A's d'tor will be called?

    The implementation will always destroy the exception object properly regardless of how it is caught. The implementation constructs the exception object, so it knows how to destroy it. This is not the same as when you call delete through a pointer, because in that case there is incomplete information about the complete type of the object at that point (it may have been newed somewhere else) unless a virtual destructor exists.

    Were this not the case, catch (...) would never work at all.