The three cornerstones of Object-Oriented Programming are encapsulation, inheritance and polymorphism. Previous examples have demonstrated how data can be encapsulated within a C++ class and how derived classes inherit the properties of their base class. This chapter introduces the final cornerstone principle of polymorphism.
The term 'Polymorphism' (from the Greek meaning 'many forms') describes the ability to assign a different meaning, or purpose, to an entity according to its context.
In C++, overloaded operators can be described as polymorphic. For instance, the * character can represent either the multiply operator or the dereference operator according to its context. More importantly, C++ has the ability to bind specific derived class objects to base class pointers to create polymorphic methods.
The key to creating a polymorphic method is to first declare a 'virtual' base class method - this is just a regular declaration preceded by the virtual keyword. The declaration of a virtual method indicates that the class will be used as a base class from which another class will be derived. This derived class will contain a method to override the virtual base method.
A pointer to the base class can be assigned an object of the derived class. This pointer can be used to access regular methods of the base class and overriding methods of the derived class. For instance, this statement assigns a new Pigeon class object (derived from the Bird base class) to a pointer to the Bird base class:
Bird *pBird = new Pigeon;
Almost magically, this pointer can be used to access regular methods of the Bird base class and overriding methods of the derived Pigeon class.
The example listed demonstrates this technique in action. Two methods named Walk and Talk are declared in the base class - but only Talk is a virtual method. When the Talk method is called it executes the overriding method in the derived class, rather than the default statement in the base class, unless the base method is called explicitly.