Polymorphism in C++
Overview
Polymorphism means many forms. It is an object-oriented programming concept that refers to the ability of a variable, function, or object to take on multiple forms, which are when the behavior of the same object or function is different in different contexts.
Polymorphism can occur within the class and when multiple classes are related by inheritance.
What is Polymorphism in C++?
Polymorphism word is the combination of "poly," which means many + "morphs," which means forms, which together means many forms. Polymorphism in C++ is when the behavior of the same object or function is different in different contexts. Let's take a real-world example of the word right can mean different things in a different context.
- I was right. In the above sentence, the word right means "correct".
- Please take a right turn. The word right refers to the "right direction" in the above sentence.
Example Of Polymorphism in C++
The + operator in C++ is one of the best examples of polymorphism. The + operator is used to add two integers as follows :
Output:
In the above example, + is used to add and , the output Value of is : 42.
However, + is also used to concatenate two string operands. The + operator is used to concatenate two strings as follows :
Output:
In the above example, + is used to concatenate two strings = poly and = morphism, therefore the output Value of is polymorphism.
Types of Polymorphism in C++
Following are the two types of polymorphism in C++ :
- Compile Time Polymorphism
- Runtime Polymorphism
Compile Time Polymorphism
Compile-time polymorphism is done by overloading an operator or function. It is also known as "static" or "early binding".
Why is it called compile-time polymorphism?
Overloaded functions are called by comparing the data types and number of parameters. This type of information is available to the compiler at the compile time. Thus, the suitable function to be called will be chosen by the C++ compiler at compilation time.
There are the following types of compile-time polymorphism in C++ :
Function Overloading
When we have two functions with the same name but different parameters, different functions are called depending on the number and data types of parameters. This is known as function overloading
Function Overloading can be achieved through the following two cases:
- The names of the functions and return types are the same but differ in the type of arguments.
- The name of the functions and return types are the same, but they differ in the number of arguments.
Let's understand with an example :
Output :
Explanation:
- In the above example, the add function is overloaded.
- t1 is the object of class Temp, t1.add(10). It will call void add(int y).
- t1.add(11.1), it will call void add(double d).
- t1.add(12,13), it will call void add(int y, int z).
- The overloaded functions are called by matching the type and number of arguments. Because this information is available at compile-time, the compiler selects the proper function based on its parameters.
Operator Overloading
When an operator is updated to be used for user-defined data types (objects etc.), this is known as operator overloading. To use operator overloading, at least one operand must be a user-defined data type.
Note:
- A user-defined type must be present in at least one operand.
- ".", "::", typeid, size, ".*", and C++'s single ternary operator, "?:", are among the operators that cannot be overloaded.
These are some of the operators that can be overloaded in C++ :
Arithmetic operators : - , + , / , * , % and -=, +=, /= , *= , %=
Boolean algebra : !=, ==, > ,< ,>=, <= , && ,||
Bit manipulation : &, |, ^ ,<< ,>> and |=, &= ,>>=, <<=, ^=
Memory management : new[], new, delete[], delete
Note:
- New and Delete operators can be overloaded globally, or they can be overloaded for specific classes. If these operators are overloaded using the member function for a class, they are overloaded only for that specific class.
Syntax :
Output :
Explanation:
- In the above example, the ++ operator is overloaded for a user-defined data type, an object of the Count class.
- Count c1(42); creates the object of Count type, in which data member x will have a value equal to 42.
- Count c2 = ++c1; this calls the ++ operator function on t1, which makes the value of x as 43.
Runtime Polymorphism
Runtime polymorphism occurs when functions are resolved at runtime rather than compile time when a call to an overridden method is resolved dynamically at runtime rather than compile time. It's also known as late binding or dynamic binding.
Runtime polymorphism is achieved using a combination of function overriding and virtual functions.
The following sections will show an example of overriding with and without the virtual keyword.
Function Overriding without Virtual Keyword
Function Overriding is when more than one method of the derived class has the same name, the same number of parameters, and the same parameter type as of base class.
Syntax :
Output:
Explanation:
- In this example, the width, height, and functions set values and area are shared by all three classes (Polygon, Rectangle, and Triangle).
- Three references to Polygon are declared in the main function (ppoly1, ppoly2, and ppoly3 ). These are given the addresses rect and trgl poly, which are objects of type Rectangle, Triangle, and Polygon, respectively. Rectangle and Triangle are Polygon-derived classes; therefore, such assignments are permitted.
- ppoly1 -> set_values (10, 20); is similar to rect.set_values (10, 20); and ppoly2 -> set_values (10, 20); is similar to trgl.set_values (10, 20);
- ppoly1 -> area() and ppoly1 -> area() is called this will call area function of the base class Polygon.
- This happens due to static linkage, which implies that the compiler only sets the call to the area() once in the base class.
- To overcome this problem, the concept of virtual pointers is introduced.
Function Overriding with Virtual Keyword
A virtual function in C++ is a base class member function. In a derived class, we can redefine it. The virtual function must be declared using the keyword virtual in the base class. A class that declares or inherits a virtual function is called a polymorphic class.
Syntax :
Output:
Explanation:
- ppoly1 -> area() is called it will call area function of Rectangle class.
- ppoly2 -> area() is called it will call area function of Triangle class.
- This is because we used the virtual keyword to make the base class Polygon method area virtual in this code. The confusion over which function to call will be resolved at runtime, resulting in the desired outcome.
Pure Virtual Function
A Pure Virtual Function is a virtual function declared in the base class without definition. In simple words, it does nothing in the base class. But the derived class must provide an implementation for this function. Otherwise, we'll get a compilation error.
Syntax :
Output:
Explanation:
- Base *b1; a pointer to an object of the base class is created.
- b1 = new Derived(), b1 is now an object of Derived class.
- b1 -> func() will call the func() of the Derived class because it was declared as a virtual function in the Base class.
To check what error we get if we don't provide the definition of func() in Derived, comment out the definition and re-compile the above code. We get the following error:
Compile-Time Polymorphism Vs. Run-Time Polymorphism
Compile Time Polymorphism | Run-Time Polymorphism |
---|---|
At Compile time, which functions to be called is decided. | At Runtime, which function to be called is decided. |
Also known as early or static binding | Also known as late or dynamic binding |
It executes faster because the function is resolved at compilation time only. | It executes slower because the function is resolved at Run-time. |
It is achieved through function and operator overloading | It is achieved through function overriding and virtual functions |
Unlock the world of C++ programming with our C++ full course designed by industry experts. Enroll now and excel in coding.
Conclusion
- Polymorphism in C++ is when the behavior of the same object or function is different in different contexts.
- It is of two types: Compile-time Polymorphism and Runtime Polymorphism.
- In Compile Time Polymorphism, the function to be invoked is decided at the compile time only. It is achieved using a function or operator overloading.
- In Runtime Polymorphism, the function invoked is decided at the Run-time. It is achieved using function overriding and virtual functions.
- The virtual function must be declared using the keyword "virtual" in the base class.
- A Pure Virtual Function is a virtual function declared in the base class without definition.