1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
Destructors
hi(destructor: derived class) of classes are automatically called when an
object is destroyed. This also holds true for objects of classes derived from
other classes. Assume we have the following situation:
verb(
class Base
{
public:
~Base();
};
class Derived: public Base
{
public:
~Derived();
};
int main()
{
Derived derived;
}
)
At the end of tt(main), the tt(derived) object ceases to exists. Hence,
its destructor (tt(~Derived)) is called. However, since tt(derived) is also a
tt(Base) object, the tt(~Base) destructor is called as well. The base class
destructor is never explicitly called from the derived class destructor.
Constructors
hi(constructor: calling order) hi(destructor: calling order) and destructors
are called in a stack-like fashion: when tt(derived) is constructed, the
appropriate base class constructor is called first, then the appropriate
derived class constructor is called. When the object tt(derived) is destroyed,
its destructor is called first, automatically followed by the activation of
the tt(Base) class destructor. A i(derived class destructor) is always called
before its i(base class destructor) is called.
When the construction of a derived class objects did not successfully complete
(i.e., the constructor threw an exception) then its destructor is not
called. However, the destructors of properly constructed base classes em(will)
be called if a derived class constructor throws an exception. This, of course,
is it should be: a properly constructed object should also be destroyed,
eventually. Example:
verb(
#include <iostream>
struct Base
{
~Base()
{
std::cout << "Base destructor\n";
}
};
struct Derived: public Base
{
Derived()
{
throw 1; // at this time Base has been constructed
}
};
int main()
{
try
{
Derived d;
}
catch(...)
{}
}
/*
This program displays `Base destructor'
*/
)
|