Will the destructor of the base class be called if an object throws an exception in the constructor?
If an exception is thrown during construction, all previously constructed sub-objects will be properly destroyed. The following program proves that the base is definitely destroyed:
struct Base
{
~Base()
{
std::cout << "destroying base\n";
}
};
struct Derived : Base
{
Derived()
{
std::cout << "throwing in derived constructor\n";
throw "ooops...";
}
};
int main()
{
try
{
Derived x;
}
catch (...)
{
throw;
}
}
output:
throwing in derived constructor
destroying base
(Note that the destructor of a native pointer does nothing, that's why we prefer RAII over raw pointers.)