< Previous | Contents | Next >

Instantiating Objects from a Derived

Class

In main(), I instantiate an Enemy object and then call its Attack() member function. This works just as youd expect. The interesting part of the program begins next, when I instantiate a Boss object.

Boss boss1;

After this line of code, I have a Boss object with an m_Damage data member equal to 10 and an m_DamageMultiplier data member equal to 3. How did this happen? Although constructors and destructors are not inherited from a base class, they are called when an instance is created or destroyed. In fact, a base class constructor is called before the derived class constructor to create its part of the final object.

In this case, when a Boss object is instantiated, the default Enemy constructor is automatically called and the object gets an m_Damage data member with a value of 10 (just like any Enemy object would). Then, the Boss constructor is called and finishes off the object by giving it an m_DamageMultiplier data member with a value of 3. The reverse happens when a Boss object is destroyed at the end of the program. First, the Boss class destructor is called for the object, and then the

Controlling Access under Inheritance 337


Enemy class destructor is called. Because I didnt define destructors in this program, nothing special happens before the Boss object ceases to exist.


Hin t

image

The fact that base class destructors are called for objects of derived classes ensures that each class gets its chance to clean up any part of the object that needs to be taken care of, such as memory on the heap.

image