|
|
|
|
|
|
|
LISTING 16.6 HIDING METHODS |
|
|
|
 |
|
|
|
|
1: //Listing 16.6 Hiding methods
2:
3: #include <iostream.h>
4:
5: class Mammal
6: {
7: public:
8: void Move() const { cout << Mammal move one step\n; }
9: void Move(int distance) const
10: {cout << Mammal move << distance << steps.\n; }
11: protected:
12: int itsAge;
13: int itsWeight;
14: };
15:
16: class Dog : public Mammal
17: {
18: public:
19: void Move() const { cout << Dog move 5 steps.\n; }
20: }; // You may receive a warning that you are hiding a function!
21:
22: int main()
23: {
24: Mammal bigAnimal;
25: Dog fido;
26: bigAnimal.Move();
27: bigAnimal.Move(2);
28: fido.Move();
29: // fido.Move(10);
30: return 0;
31: } |
|
|
|
|
|
|
|
|
Mammal move one step
Mammal move 2 steps
Dog move 5 steps |
|
|
|
|
|
|
|
|
Analysis: All the extra methods and data have been removed from these classes. On lines 8 and 9, the Mammal class declares the overloaded Move() methods. On line 19, Dog overrides the version of Move() with no parameters. These are invoked on lines 2628, and the output reflects this as executed. |
|
|
|
|
|
|
|
|
Line 29, however, is commented out, as it causes a compile-time error. Although the Dog class could have called the Move(int) method if it had not overridden the version of Move() without parameters, now that it has done so it must override both if it wants to use both. This is reminiscent of the rule that states if you supply any constructor, the compiler will no longer supply a default constructor. |
|
|
|
|
|