functions enable you to do that. To create a virtual function, you add the keyword vir-
tualin front of the function declaration. Listing 12.8 illustrates how this works, and
what happens with nonvirtual methods.
LISTING12.8 Using Virtual Methods
1: //Listing 12.8 Using virtual methods
2: #include <iostream>
3: using std::cout;
4:
5: class Mammal
6: {
7: public:
8: Mammal():itsAge(1) { cout << “Mammal constructor...\n”; }
9: virtual ~Mammal() { cout << “Mammal destructor...\n”; }
10: void Move() const { cout << “Mammal move one step\n”; }
11: virtual void Speak() const { cout << “Mammal speak!\n”; }
12:
13: protected:
14: int itsAge;
15: };
16:
17: class Dog : public Mammal
18: {
19: public:
20: Dog() { cout << “Dog Constructor...\n”; }
21: virtual ~Dog() { cout << “Dog destructor...\n”; }
22: void WagTail() { cout << “Wagging Tail...\n”; }
23: void Speak()const { cout << “Woof!\n”; }
24: void Move()const { cout << “Dog moves 5 steps...\n”; }
25: };
26:
27: int main()
28: {
29: Mammal *pDog = new Dog;
30: pDog->Move();
31: pDog->Speak();
32:
33: return 0;
34: }
Mammal constructor...
Dog Constructor...
Mammal move one step
Woof!
On line 11,Mammalis provided a virtual method—Speak(). The designer of this
class thereby signals that she expects this class eventually to be another class’s
base type. The derived class will probably want to override this function.
OUTPUT
392 Day 12
ANALYSIS