OOPortal OOPortal

Ad Hoc Polymorphism  «Prev  Next»
Lesson 2 Designing Reusable Polymorphism
Objective Define polymorphism and explain why it is central to OOP.

Why is Polymorphism central to Object Oriented Programming

Polymorphism is a way of giving different meanings to the same message. The meanings are dependent on the type of data being processed. Object orientation takes advantage of polymorphism by linking behavior to the object's type. In addition, polymorphism localizes responsibility for behavior. The client code frequently requires no revision when additional functionality is added to the system through implementor-provided code additions.
In effect, polymorphism is the genie in OOP, taking instruction from a client and properly interpreting its wishes.

Polymorphism in the context of object-oriented programming is the ability of one type alpha to appear as and be used like another type beta. The purpose of polymorphism is to implement a style of programming called message-passing in which objects of various types define a common interface of operations for users.
In strongly typed languages, polymorphism usually means that type alpha somehow derives from type beta, or type gamma implements an interface that represents type beta. In weakly typed languages types are implicitly polymorphic.

To begin, examine this short example:
#include <iostream>
using namespace std;
class base {
 virtual void vfunc() {
  cout << "This is base's vfunc().\n";
class derived1 : public base {
  void vfunc() {
  cout << "This is derived1's vfunc().\n";
class derived2 : public base {
 void vfunc() {
 cout < <"This is derived2's vfunc().\n";

int main(){
 base *p, b;
 derived1 d1;
 derived2 d2;
 // point to base
 p = &b;
 p->vfunc(); // access base's vfunc()
 // point to derived1
 p = &d1;
 p->vfunc(); // access derived1's vfunc()
 // point to derived2
 p = &d2;
 p->vfunc(); // access derived2's vfunc()
 return 0;

This program displays the following:
This is base's vfunc().
This is derived1's vfunc().
This is derived2's vfunc().

As the program illustrates, inside base, the virtual function vfunc() is declared. Notice that the keyword virtual precedes the rest of the function declaration. When vfunc() is redefined by derived1 and derived2, the keyword virtual is not needed. (However, it is not an error to include it when redefining a virtual function inside a derived class; it's just not needed.)