Polymorphism

From Greek, meaning many (poly) forms (morph), provides the ability to assign different meanings or functionality to an object depending on its context.

 

Polymorphism is the process of taking a derived class object, assigning it to a base class type and invoking the correct (virtual) function according to the derived class type.

 

This allows an abstracted method of programming that focuses on generalised code, so that a programmer needs only to know about the interface and not its implementation. Allows: same interface, different implementation, by using / invoking the same method (behaviour) identifier (e.g. talk() which might result in: moo, meow, grr, hello) based on the object invoking the method.

 

Since derived classes are inherited from base classes, they are type compatible, i.e. a derived class is a form of a base class.  Therefore any derived class of a base class can invoke the methods inherited (and overridden) from the base class.

 

Polymorphism is realised when the base class methods are made virtual, which instructs the compiler to implement code that will select the correct derived class method at run time using late binding, instead of type of the pointer to determine which to call.

 

Polymorphism allows generalisation (abstraction) and since all the methods are inherited in the derived classes, it's not 'really' calling the base method name - it's simply calling the method name, which is selected by the derived object type. It's all about type!

 

Polymorphism allows the language to become object oriented, true it needs the other pillars (encapsulation and inheritance), but this is where OOP truly becomes possible since it enables abstraction, the ability to loosely say I want one of these to do this, e.g. animal, make sound

Leave a Reply