Sams Teach Yourself C++ in 21 Days

(singke) #1
Implementing Inheritance 387

12


Mammal constructor...
Mammal constructor...
Dog constructor...
Mammal sound!
Woof!
Dog destructor...
Mammal destructor...
Mammal destructor...
Looking at the Mammalclass, you can see a method called Speak()defined on
line 15. The Dogclass declared on lines 23–37 inherits from Mammal(line 23),
and, therefore, has access to this Speak()method. The Dogclass, however, overrides this
method on line 33, causing Dogobjects to say Woof!when the Speak()method is called.
In the main()function, a Mammalobject,bigAnimal, is created on line 41, causing the
first line of output when the Mammalconstructor is called. On line 42, a Dogobject,Fido,
is created, causing the next two lines of output, where the Mammalconstructor and then
the Dogconstructor are called.
On line 43, the Mammalobject calls its Speak()method; then on line 44, the Dogobject
calls its Speak()method. The output reflects that the correct methods were called. The
bigAnimalmade a mammal sound and Fidowoofed. Finally, the two objects go out of
scope and the destructors are called.

OUTPUT


ANALYSIS


Overloading Versus Overriding
These terms are similar, and they do similar things. When you overload a method, you
create more than one method with the same name, but with a different signature. When
you override a method, you create a method in a derived class with the same name as a
method in the base class and the same signature.

Hiding the Base Class Method ......................................................................


In the previous listing, the Dogclass’s Speak()method hides the base class’s method.
This is what is wanted, but it can have unexpected results. If Mammalhas a method,
Move(), which is overloaded, and Dogoverrides that method, the Dogmethod hides all the
Mammalmethods with that name.
If Mammaloverloads Move()as three methods—one that takes no parameters, one that
takes an integer, and one that takes an integer and a direction—and Dogoverrides just the
Move()method that takes no parameters, it will not be easy to access the other two meth-
ods using a Dogobject. Listing 12.6 illustrates this problem.
Free download pdf