< previous page page_265 next page >

Page 265
LISTING 16.7 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
30:       Mammal bigAnimal;
31:       Dog fido;
32:       bigAnimal.Move(2);
33:       fido.Mammal::Move(6);
34:       return 0;
35:    }

Output:
Mammal move 2_steps
Mammal move 6_steps
Analysis: On line 30, a Mammal, bigAnimal, is created; and on line 31, a Dog, Fido, is created. The method call on line 32 invokes the Move() method of Mammal, which takes an int.
The programmer wants to invoke Move(int) on the Dog object, but has a problem. Dog overrides the Move() method, but does not overload it and does not provide a version that takes an int. This is solved by the explicit call to the base class Move(int) method on line 33.
DODON'T
DO extend the functionality of tested classes by deriving.DON'T hide a base class function by changing the function signature.
DO change the behavior of certain functions in the derived class by overriding the base class methods.

Summary
In this hour, you learned how derived classes inherit from base classes. Classes inherit all the public and protected data and functions from their base classes.
Protected access is public to derived classes and private to all other objects. Even derived classes cannot access private data or functions in their base classes.
Constructors can be initialized before the body of the constructor. It is at this time that base constructors are invoked and parameters can be passed to the base class.
Functions in the base class can be overridden in the derived class. If the base class functions are virtual, and if the object is accessed by pointer or reference, the derived class's functions will be invoked based on the runtime type of the object pointed to.

 
< previous page page_265 next page >

If you like this book, buy it!