Sams Teach Yourself C++ in 21 Days

(singke) #1
Implementing Inheritance 385

12


The implementation for the Dogconstructor, which takes an integer, is on lines 81–86. In
its initialization phase (lines 82 and 83),Doginitializes its base class, passing in the para-
meter, and then it initializes its breed.
Another Dogconstructor is on lines 88–94. This constructor takes two parameters. Once
again, it initializes its base class by calling the appropriate constructor on line 89, but this
time it also assigns weight to its base class’s variable itsWeight. Note that you cannot
assign to the base class variable in the initialization phase. Because Mammaldoes not have
a constructor that takes this parameter, you must do this within the body of the Dog’s
constructor.
Walk through the remaining constructors to be certain you are comfortable with how
they work. Note what is initialized and what must wait for the body of the constructor.
The output has been numbered so that each line can be referred to in this analysis. The
first two lines of output represent the instantiation of Fido, using the default constructor.
In the output, lines 3 and 4 represent the creation of rover. Lines 5 and 6 represent
buster. Note that the Mammalconstructor that was called is the constructor that takes one
integer, but the Dogconstructor is the constructor that takes two integers.
After all the objects are created, they are used and then go out of scope. As each object is
destroyed, first the Dogdestructor and then the Mammaldestructor is called, five of each in
total.

Overriding Base Class Functions ........................................................................


A Dogobject has access to all the data members and functions in class Mammal, as well as
to any of its own data members and functions, such as WagTail(), that the declaration of
the Dogclass might add. A derived class can also override a base class function.
Overriding a function means changing the implementation of a base class function in a
derived class.
When a derived class creates a function with the same return type and signature as a
member function in the base class, but with a new implementation, it is said to be over-
riding that function. When you make an object of the derived class, the correct function
is called.
When you override a function, its signature must agree with the signature of the function
in the base class. The signature is the function prototype other than the return type; that
is, the name of the function, the parameter list, and the keyword const, if used. The
return types might differ.
Free download pdf