Polymorphism Implemented With Virtual Methods

The previous chapter emphasized the fact that a Dog object is a Mammal object. So far that has meant only that the Dog object has inherited the attributes (data) and capabilities (methods) of its base class. In C++, the is-a relationship runs deeper than that, however.

Polymorphism allows you to treat derived objects as if they were base objects. For example, suppose you create a number of specialized Mammal types: Dog, Cat, Horse, and so forth. All of these derive from Mammal, and Mammal has a number of methods which are factored out of the derived classes. One such method might be Speak(). All mammals can make noise.

You'd like to teach each of the derived types to specialize how they speak. A Dog ...

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.