Breaking News

Polymorphism In C++

Poly means many. Polymorphism basically means many forms.

As a simple example: there are many English words which have a different meaning depending on the context of use.

Basically, the word is the same word but it’s interpretation varies depending on the use. Similarly, in C++ we can make use of polymorphism.

For example: consider operator overloading. You may have created an overloaded + operator to concatenate two strings. Now, the + sign can be used to add two strings (because you overloaded it) and it can even be used to add two numbers (which was it’s actual use).

Depending on the type of data being operated on, the compiler will decide on which function to use. If the operands are numbers, then it will use the normal function.

This is a type of polymorphism.

Therefore we have to distinguish different types of polymorphism which will be outlined here.

The first type is similar to the concept of dynamic binding. Here, the type of a variable depends on its content. Thus, its type depends on the content at a specific time:

v := 123 /* v is integer */

… /* use v as integer */

v := ‘abc’ /* v “switches” to string */

… /* use v as string */

The concept of dynamic binding allows a variable to take different types dependent on the content at a particular time. This ability of a variable is called polymorphism.

Another type of polymorphism can be defined for functions.

For example, suppose you want to define a function isNull() which returns TRUE if its argument is 0 (zero) and FALSE otherwise. For integer numbers this is easy:

boolean isNull(int i) {

if (i == 0) then
return TRUE
else
return false
end if
}

However, if we want to check this for real numbers, we should use another comparison due to the precision problem:

boolean isNull(real r) {

if (r < 0.01 and r > -0.99) then
return True
else
return False
end if
}

In both cases we want the function to have the name isNull. In programming languages without polymorphism for functions we cannot declare these two functions because the name isNull would be doubly defined.

Without polymorphism for functions, doubly defined names would be ambiguous. However, if the language would take the parameters of the function into account it would work.

Thus, functions (or methods) are uniquely identified by:

The name of the function (or method) and The types of its parameter list.

Objects of superclasses can be filled with objects of their subclasses. Operators and methods ofsubclasses can be defined to be evaluated in two contexts:

Based on object type, leading to an evaluation within the scope of the superclass.

Based on object content, leading to an evaluation within the scope of the contained subclass.

The second type is called polymorphism.

Check Also

Insertion & Extraction In C++

Insertion is the operation of sending characters to a stream, expressed by the overloaded insertion …