Page 210 - DCAP404 _Object Oriented Programming
P. 210
Unit 9: Inheritance
Notes
Notes Note that B is initialized/called first, although it appears second in the derived
constructor. This is because it has been declared first in the derived class header line. Also
note that A(a1) and B(b1) are function calls. Therefore the parameter should not include
types.
9.7 Destructors under Inheritance
If a derived class doesn’t explicitly call a constructor for a base class, the default constructor for
the parent class. In fact, the constructors for the parent classes will be called from the ground up.
For example, if you have a base class Vehicle and Car inherits from it, during the construction of
a Car, it becomes a Vehicle and then becomes a Car.
Destructors for a base class are called automatically in the reverse order of constructors.
One thing to think about is with inheritance you may want to make the destructors virtual:
class Vehicle {
public:
~Vehicle();
};
This is important if you ever need to delete a derived class when all you have is a pointer to the
base class. Say you have a “Vehicle *v” and you need to delete it. So you call:
delete v;
If Vehicle’s destructor is non-virtual and this happens to actually by a Car *”, the destructor will
not call Car::~Car() - just Vehicle::~Vehicle()
The Destructor Execution Order
1. As the objects go out of scope, they must have their destructors executed also, and since we
didn’t define any, the default destructors will be executed.
2. Once again, the destruction of the base class object named unicycle is no problem, its
destructor is executed and the object is gone.
3. The sedan_car object however, must have two destructors executed to destroy each of its
parts, the base class part and the derived class part. The destructors for this object are
executed in reverse order from the order in which they were constructed.
4. In other words, the object is dismantled in the opposite order from the order in which it
was assembled. The derived class destructor is executed first, then the base class destructor
and the object is removed from the allocation.
5. Remember that every time an object is instantiated, every portion of it must have a
constructor executed on it. Every object must also have a destructor executed on each of its
parts when it is destroyed in order to properly dismantle the object and free up the
allocation. Compile and run this program.
LOVELY PROFESSIONAL UNIVERSITY 203