class A { \fbox{A}
public:
A() { cout << "A"; }
~A() { cout << "A"; }
};
class B : public A { \fbox{B}
public:
B() { cout << "B"; }
~B() { cout << "B"; }
};
slide: Constructors and destructors
Memory management in C++ involves
the use of constructors and destructors.
In the following, we will look
at some examples illustrating the order
of invocation of constructors and destructors
in relation to single and multiple inheritance.
The first example, given in slide [2-m-1],
defines two classes (A and B,
with B derived from A),
each having a constructor and destructor
writing the name of the class to standard output.
An example of their use is:
A* a = new B; delete a; ABA
B* b = new B; delete b; ABBA
Recall that when creating an instance of
a class, the constructors of the base classes
(if any) are called first.
This is exactly what happens above.
However, contrary to what is expected,
when deleting a, the destructor for B
is not called, whereas it is invoked when deleting
b.
class A { \fbox{A}
public:
A() { cout << "A"; }
virtual ~A() { cout << "A"; }
};
slide: Virtual destructors
The remedy to this is to declare the destructor
of A virtual, as in slide [2-m-2], since it dynamically
invokes the destructor declared for the
actual class type $(B)