< previous page page_282 next page >

Page 282
LISTING 18.1 VIRTUAL METHODS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     // Listing 18.1 - virtual methods
2:
3:    #include <iostream.h>
4:    class Mammal
5:    {
6:    public:
7:       Mammal():itsAge(1) { cout << Mammal constructor\n; }
8:       virtual ~Mammal() { cout << Mammal destructor\n; }
9:       virtual void Speak() const { cout << Mammal speak!\n; }
10:    protected:
11:      int itsAge;
12:   };
13:
14:   class Cat: public Mammal
15:   {
16:   public:
17:      Cat() { cout << Cat constructor\n; }
18:      ~Cat() { cout << Cat destructor\n; }
19:      void Speak()const { cout << Meow!\n; }
20:   };
21:
22:   int main()
23:   {
24:      Mammal *pCat = new Cat;
25:      pCat->Speak();
26:      return 0;
27:   }

Output:
Mammal constructor
Cat Constructor
Meow!
Analysis: On line 9, Speak() is declared to be a virtual method; it is overridden on lines 19 and invoked on line 25. Note, again, that pCat is a declared to be a pointer to Mammal, but the address of a Cat is assigned to it. This is, as discussed in Hour 17, Polymorphism and Derived Classes, the essence of polymorphism.
What happens, however, if you want to add a method to Cat that is inappropriate for Mammal? For example, suppose you want to add a method called Purr(). Cats purr, but no other mammals do. You would declare your class like this:
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
class Cat: public Mammal
{
public:
   Cat() { cout << Cat constructor\n; }
   ~Cat() { cout << Cat destructor\n; }

 
< previous page page_282 next page >

If you like this book, buy it!