> Some amount of memory is allocated inside the Base Constructor using
new. During the construction of a derived object an exception occurred
in the constructor of the derived class.
Will the memory get de allocated which got allocated in Base class
constructor? Will the Base class destructor get called?
class Base
{
int *p;
public:
B() { p = new int[100]; }
~B() { delete[] p; }
};
class Derived : public Base
{
public:
Derived ()
{
/* Exception Occurred!!!!!!!!!!!!! */
}
The short answer is: Yes. The base destructor is guaranteed to be
called. And any objects in the base class and the derived class already
constructed (i.e. aggregate objects). But the tricky part is that the
destructor of the derived object itself is *not* called. The destructor
is only called for fully contructed objects.
So, if you do any non-managed allocation in the constructor you need to
use try/catch and cleanup the memory before exiting the constructor
(since your destructor will *not* be called in this case). Try to use
RAII objects like smart_ptr or auto_ptr to handle memory allocations
and deallocations automatically in case of exceptions.
But the nice thing is that all other objects - base object(s) and
aggregate objects will be destructed as expected.
/ Påhl