Polymorphism in C++ and Types of Polymorphism in C

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Polymorphism in C++ and Types of Polymorphism in C++

https://www.mygreatlearning.com/blog/polymorphism-in-cpp/

Polymorphism In C++ and Types of Polymorphism


By Great Learning Team Updated on Nov 23, 2022 121179
Table of contents

What is Polymorphism in C++?


Types of Polymorphism in C++
Difference between run-time and compile-time
A real-time example of polymorphism in C++
C++ runtime polymorphism example

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:

What is Polymorphism in C++?

Polymorphism in C++ means, the same entity (function or object) behaves differently in different scenarios.

Consider this example:

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.

string firstName = "Great ";


string lastName = "Learning";

// name = "Great Learning "


string name = firstName + lastName;

Types of Polymorphism in C++

Polymorphism in C++ is categorized into two types. The figure below shows the types:

1. Compile Time Polymorphism

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++.

II. Operator Overloading

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

The result of the addition of two objects is: Welcomeback

C++ Tutorial PDF

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……

II. Virtual Function

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

1 //without virtual Function


2
3 #include <iostream>
using namespace std;
4
class Add
5
{
6 int x=5, y=20;
7 public:
8 void display() //overridden function
9 {
10 cout << "Value of x is : " << x+y<<endl;
}
11 };
12 class Substract: public Add
13 {
int y = 10,z=30;
14
public:
15 void display() //overridden function
16 {
17 cout << "Value of y is : " <<y-z<<endl;
18 }
19 };
20 int main()
21 {
Add *m; //base class pointer .it can only access the base class
22 members
23 Substract s; // making object of derived class
24 m = &s;
25 m->display(); // Accessing the function by using base class pointer
return 0;
26
}
27
28
29
30

Output

Value of x is: 25

Virtual Function used to invoke the derived class in a program.

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

derived class Action:10

show base class

Pure Virtual Function

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

Difference between run-time and compile-time

Run-time Compile-time

1)Compile time is the time period where the


code typed is converted into executable
code.
1)Run time is the time period where the 2)Errors are detected before the execution of
executable code is running. the program.
2)Errors can be detected only after the execution 3)Errors that occur during compile time are
of the program. called compile-time errors. Two types of
3)Errors that occur during the execution of a compile-time errors area)
program are called run-time errors. Run time a) semantics error occurs when the
errors aren’t detected by the compiler. statements aren’t meaningful to the
compiler.
b)Syntax error occurs when the programmer
doesn’t follow the syntax.

A real-time example of polymorphism in C++

A topic can be understood clearly when we compare it to a real time example.

Let’s discuss few real time examples of polymorphism in C++

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.

C++ runtime polymorphism example

#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.

You might also like