LISTING12.6 Hiding Methods
1: //Listing 12.6 Hiding methods
2: #include <iostream>
3: using std::cout;
4:
5: class Mammal
6: {
7: public:
8: void Move() const { cout << “Mammal move one step.\n”; }
9: void Move(int distance) const
10: {
11: cout << “Mammal move “;
12: cout << distance <<” steps.\n”;
13: }
14: protected:
15: int itsAge;
16: int itsWeight;
17: };
18:
19: class Dog : public Mammal
20: {
21: public:
22: // You might receive a warning that you are hiding a function!
23: void Move() const { cout << “Dog move 5 steps.\n”; }
24: };
25:
26: int main()
27: {
28: Mammal bigAnimal;
29: Dog Fido;
30: bigAnimal.Move();
31: bigAnimal.Move(2);
32: Fido.Move();
33: // Fido.Move(10);
34: return 0;
35: }
Mammal move one step.
Mammal move 2 steps.
Dog move 5 steps.
All the extra methods and data have been removed from these classes. On lines 8
and 9, the Mammalclass declares the overloaded Move()methods. On line 23,Dog
overrides the version of Move()with no parameters. These methods are invoked on lines
30–32, and the output reflects this as executed.
Line 33, however, is commented out because it causes a compile-time error. After you
override one of the methods, you can no longer use any of the base methods of the same
OUTPUT
388 Day 12
ANALYSIS