Polymorphism in C++ and Types of Polymorphism in C
Polymorphism in C++ and Types of Polymorphism in C
https://www.mygreatlearning.com/blog/polymorphism-in-cpp/
When the same entity (function or object) behaves differently in different scenarios, it is known as Polymorphism in C++.
The topics Covered Under Polymorphism in C++ are:
Polymorphism in C++ means, the same entity (function or object) behaves differently in different scenarios.
The “ +” operator in c++ can perform two specific functions at two different scenarios i.e when the “+” operator is used in
numbers, it performs addition.
int a = 6;
int b = 6;
int sum = a + b; // sum =12
And the same “+” operator is used in the string, it performs concatenation.
Polymorphism in C++ is categorized into two types. The figure below shows the types:
In compile-time polymorphism, a function is called at the time of program compilation. We call this type of polymorphism as
early binding or Static binding.
Function overloading and operator overloading is the type of Compile time polymorphism.
I. Function Overloading
Function overloading means one function can perform many tasks. In C++, a single function is used to perform many tasks
with the same name and different types of arguments. In the function overloading function will call at the time of program
compilation. It is an example of compile-time polymorphism.
In the below example, A function ADD() is used to perform two tasks. The two asks would be to add two integer values and
add two strings (concatenate).
Readability of the program increases by function overloading. It is achieved by using the same name for the same action.
Source Code:
1
2 #include <iostream>
3 using namespace std;
4 class Addition {
5 public:
int ADD(int X,int Y) // Function with parameter
6
{
7 return X+Y; // this function is performing addition of two Integer
8 value
9 }
10 int ADD() { // Function with same name but without parameter
11 string a= "HELLO";
12 string b="SAM"; // in this function concatenation is performed
string c= a+b;
13 cout<<c<<endl;
14
15 }
16 };
17 int main(void) {
18 Addition obj; // Object is created
cout<<obj.ADD(128, 15)<<endl; //first method is called
19 obj.ADD(); // second method is called
20 return 0;
21 }
22
Output
143
HELLOSAM
In the above example, we use function ADD() to perform many tasks which is a property of polymorphism in C++.
Operator overloading means defining additional tasks to operators without changing its actual meaning. We do this by using
operator function.
The purpose of operator overloading is to provide a special meaning to the user-defined data types.
The advantage of Operators overloading is to perform different operations on the same operand.
Source Code
1 #include <iostream>
2 using namespace std;
3 class A
4 {
5
string x;
6 public:
7 A(){}
8 A(string i)
9 {
10 x=i;
}
11 void operator+(A);
12 void display();
13 };
14
15 void A:: operator+(A a)
16 {
17
18 string m = x+a.x;
19 cout<<"The result of the addition of two objects is : "<<m;
20
}
21 int main()
22 {
23 A a1("Welcome");
24 A a2("back");
25 a1+a2;
return 0;
26
}
27
28
29
30
Output
2. Runtime Polymorphism
In a Runtime polymorphism, functions are called at the time the program execution. Hence, it is known as late binding or
dynamic binding.
Function overriding is a part of runtime polymorphism. In function overriding, more than one method has the same name
with different types of the parameter list.
It is achieved by using virtual functions and pointers. It provides slow execution as it is known at the run time. Thus, It is
more flexible as all the things executed at the run time.
I. Function overriding
In function overriding, we give the new definition to base class function in the derived class. At that time, we can say the
base function has been overridden. It can be only possible in the ‘derived class’. In function overriding, we have two
definitions of the same function, one in the superclass and one in the derived class. The decision about which function
definition requires calling happens at runtime. That is the reason we call it ‘Runtime polymorphism’.
Source code
1 #include <iostream>
2 using namespace std;
3 class Animal {
4 public:
void function(){
5
cout<<"Eating..."<<endl;
6 }
7 };
8 class Man: public Animal
9 {
10 public:
void function()
11
{
12 cout<<"Walking ..."<<endl;
13 }
14 };
15 int main(void) {
16 Animal A =Animal();
A.function(); //parent class object
17 Man m = Man();
18 m.function(); // child class object
19
20 return 0;
21 }
22
23
24
Output
Eating …..
Walking……
A virtual function is declared by keyword virtual. The return type of virtual function may be int, float, void.
A virtual function is a member function in the base class. We can redefine it in a derived class. It is part of run time
polymorphism. The declaration of the virtual function must be in the base class by using the keyword virtual. A virtual
function is not static.
The virtual function helps to tell the compiler to perform dynamic binding or late binding on the function.
If it is necessary to use a single pointer to refer to all the different classes’ objects. This is because we will have to create a
pointer to the base class that refers to all the derived objects.
But, when the base class pointer contains the derived class address, the object always executes the base class function.
For resolving this problem, we use the virtual function.
When we declare a virtual function, the compiler determines which function to invoke at runtime.
Let’s see the below example for understanding how the program execution happens without virtual function and with virtual
function.
Source code
Output
Value of x is: 25
Source Code
1 #include<iostream>
2 using namespace std;
3
4 class Add
5 {
public:
6 virtual void print ()
7 { int a=20, b=30;
8 cout<< " base class Action is:"<<a+b <<endl;
9 }
10
11 void show ()
12 { cout<< "show base class" <<endl; }
13 };
14
15 class Sub: public Add
16 {
public:
17 void print () //print () is already virtual function in derived class, we could
18 also declared as virtual void print () explicitly
19 { int x=20,y=10;
20
21 cout<< " derived class Action:"<<x-y <<endl; }
22
23 void show ()
24 { cout<< "show derived class" <<endl; }
25 };
26
//main function
27 int main()
28 {
29 Add *aptr;
Sub s;
30 aptr = &s;
31
32 //virtual function, binded at runtime (Runtime polymorphism)
33 aptr->print();
34
35 // Non-virtual function, binded at compile time
aptr->show();
36
37 return 0;
38 }
39
40
41
42
Output
When the function has no definition, we call such functions as “Do-nothing function or Pure virtual function”. The declaration
of this function happens in the base class with no definition.
Source Code
1
2
#include <iostream>
3 using namespace std;
4 class Animal
5 {
6 public:
7 virtual void show() = 0; //Pure virtual function declaration.
8 };
9 class Man: public Animal
10 {
public:
11 void show()
12 {
13 cout << "Man is the part of animal husbandry " << endl;
14 }
15 };
16 int main()
17 {
Animal *aptr; //Base class pointer
18 //Animal a;
19 Man m; //derived class object creation.
20 aptr = &m;
21 aptr->show();
return 0;
22
}
23
24
Output
Man is the part of animal husbandry
Run-time Compile-time
A person can have various roles and responsibilities at the same time. A woman plays multiple roles in her life such as
a mother, wife, daughter, daughter in law, sister etc.
A man behaves as an employee in an office, son or husband at home, customer at a mall etc.
A mobile is one device but offers various features such as camera, radio etc.
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating";
}
};
class Goat: public Animal
{
public:
void eat()
{ cout<<"Eating grass";
}
};
int main(void) {
Goat g = Goat();
g.eat();
return 0;
}
Output
Run time polymorphism example with data members
#include <iostream>
using namespace std;
class Animal {
class declaration.
public:
string color = "White";
};
class Rabbit: public Animal
Animal class.
{
public:
string color = "pink";
};
int main(void) {
Animal r= Rabbit();
cout<<r.color;
}
Output
Run time polymorphism example using two derived classes
#include <iostream>
using namespace std;
class Polygon {
public:
virtual void show() {
cout<<"It is a polygon"<<endl;
}
};
class Hexagon : public Polygon {
public:
void show() {
cout<<"Hexagon is a 6 sided polygon"<<endl;
}
};
class Pentagon : public Polygon {
public:
void show() {
cout<<"Pentagon is a 5 sided polygon"<<endl;
}
};
int main() {
Polygon *P;
Hexagon h;
Pentagon p;
P = &h;
P->show();
P = &p;
P->show();
return 0;
}
Output
This brings us to end of the blog on Polymorphism in C++. Hope this helps you to up-skill your C++ skills. To learn more
about programming and other related concepts, check out the courses on Great Learning Academy.
Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro.