O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required