Problems with Single Inheritance

In the previous chapters, I discussed treating derived objects polymorphically with their base classes. You saw that if the base class has a method Speak() that is overridden in the derived class, a pointer to a base object that is assigned to a derived object will “do the right thing.” Listing 18.1 illustrates this idea.

Listing 18.1. Virtual Methods
 0: // Listing 18.1 - virtual methods 1: #include <iostream> 2: 3: class Mammal 4: { 5: public: 6: Mammal():itsAge(1) { std::cout << "Mammal constructor...\n"; } 7: virtual ~Mammal() { std::cout << "Mammal destructor...\n"; } 8: virtual void Speak() const { std::cout << "Mammal speak!\n"; } 9: protected: 10: int itsAge; 11: }; 12: 13: class Cat: public Mammal 14: ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.