< previous page page_262 next page >

Page 262
LISTING 16.5 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
41:   {
42:      Mammal bigAnimal;
43:      Dog fido;
44:      bigAnimal.Speak();
45:      fido.Speak();
46:      return 0;
47:   }

Output:
Mammal constructor
Mammal constructor
Dog constructor
Mammal sound!
Woof!
Dog destructor
Mammal destructor
Mammal destructor
Analysis: On line 34, the Dog class overrides the Speak() method, causing Dog objects to say Woof! when the Speak() method is called. On line 42, a Mammal object, bigAnimal, is created, causing the first line of output when the Mammal constructor is called. On line 43, a Dog object, fido, is created, causing the next two lines of output, where the Mammal constructor and then the Dog constructor are called.
On line 44, the Mammal object calls its Speak() method; then on line 45 the Dog object calls its Speak() method. The output reflects that the correct methods were called. Finally, the two objects go out of scope,and the destructors are called.
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 different signatures. 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 with the same signature.
Hiding the Base Class Method
In the previous listing, the Dog class's method Speak() hides the base class's method. This is just what is wanted, but it can have unexpected results. If Mammal has a Move() method that is overloaded, and Dog overrides that method, the Dog method will hide all the Mammal methods with that name.
If Mammal overloads Move() as three methodsone that takes no parameters, one that takes an integer, and one that takes an integer and a directionand Dog overrides just the Move() method, which takes no parameters, it will not be easy to access the other two methods using a Dog object. Listing 16.6 illustrates this problem.

 
< previous page page_262 next page >

If you like this book, buy it!