Sep 6, 2020

Polymorphism in C++ | C++ Language | Coding Winds

Polymorphism in C++

Hello people, today we are going to read about one of the pillar of Object-Oriented Programming Language, i.e, Polymorphism.

What is Polymorphism?

Polymorphism, a Greek term, means the ability to take more than one form. An operation may exhibit different behaviours in different instances. The behaviour depends upon the types of data used in the operation. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

In C++, polymorphism is mainly of two types :

1.    Compile Time Polymorphism

2.    Run Time Polymorphism


Compile time polymorphism

This type of polymorphism is achieved by using the function overloading and operator overloading.

1.    Function Overloading –

 

When there are multiple functions with similar name but different parameters then these functions are said to be overloaded. Functions can be overloaded by changing the types of arguments or by changing the number of arguments.

 

For better understanding look at the code below:

 


OUTPUT:

 

Coding Winds works in 3 languages

Coding Winds works in three languages

Coding Winds works in 3 languages

Thanks.

 

2.    Operator Overloading –

Operator overloading is one of the exciting features of C++ language. Operator overloading provides us the option of creating the definition of most of the C++ operators. We can overload almost every operator of C++ except of the following:

1.    Class member access operators (., .*)

2.    Scope resolution operators (::)

3.    Size operator (sizeof)

4.    Conditional operator (?:)

For better understanding look at the given below code :

OUTPUT:

3 + i6

Run time polymorphism

This type of polymorphism is achieved by using the function overriding –

1.    Function Overriding –

Function Overriding comes into action when the derived class has a definition of the member function of base class.

When we use the same function name in both the base and derived classes, the function in base class is declared as virtual using the keyword virtual preceding it’s normal declaration. When a function is made virtual, C++ determines which function to be used at the runtime based on the type of object pointed to by the base pointer, rather than the type of pointer. Thus, by making the base pointer to point to different objects, we can execute different versions of the virtual function.

 

OUTPUT:

Base Display                                                                                                                     

Base Show                                                                                                                        

Base Display                                                                                                                     

Derived Show