Polymorphism

How to develop and manage polymorphic classes. In addition to defining virtual functions, dynamic downcasting in polymorphic class hierarchies is introduced.

Concept Of Polymorphism

Example

 

Issues

If the special features of derived class objects are insignificant, you can simply concern yourself with the base members. This is the case when dynamic allocated objects are inserted into a data structure or deleted from that structure.
It makes sense to use pointers or references to the base class in this case—no matter what type of concrete object you are dealing with. However, you can only access the common base members of these objects.
However, you should be able to activate the special features of a derived class when
  • the object is accessed by a pointer or reference to the base class and
  • the concrete object type will not be known until the program is executed.
Given a base class pointer, carPtr, the statement
Example:
carPtr->display(); 
should output all the data members of the object currently being referenced.

Traditional Approach

Traditional programming languages solved this issue by adding a type field both to the base class and to the derived classes. The type field stored the type of the current class. A function that manages objects via the base class pointer could query the concrete type in a switch statement and call the appropriate method.
This solution has a disadvantage; adding derived classes at a later stage also meant adding a case label and recompiling.

Object-Oriented Approach

The approach adopted by object-oriented languages is polymorphism (Greek for multiform). In C++, virtual methods are used to implement polymorphic classes. Calling a virtual method makes the compiler execute a version of the method suitable for the object in question, when the object is accessed by a pointer or a reference to the base class!

Post a Comment

0 Comments