Types of polymorphism in c++ with example
In this C++ interview questions and answers guide, we will learn about:
-
what is polymorphism in c++?
-
types of polymorphism in c++ with example
What is polymorphism in c++?
Polymorphism is an important OOP or Object Oriented Programming concept.
Polymorphism is a Greek term which means the ability to take more than one form. In polymorphism, an operation may exhibit different behaviors in different instances.
C++ polymorphism means that a call to a member function cause a different function to be executed depending on the type of object that invokes the function. We will see this with help of program below.
Types of polymorphism in c++ with example
Polymorphism can be divided in two parts:
i) Compile time Polymorphism
ii) Run time Polymorphism
Compile time Polymorphism
An objects work/functionality is looked under the compile time of the program.
This has been done through two ways in C++:
-
function overloading, or
-
operator overloading.
class X // base class declaration.
{
int a;
public:
void display()
{
cout<< " You are in Class X ";
}
};
class Y : public X // derived class declaration.
{
int b;
public:
void display()
{
cout<<"You are in Class Y";
}
};
Run time Polymorphism
Objects method is invoked at runtime over compile time.
Run time polymorphism is acheived through virtual functions and pointers as shown below.
#include <iostream>
using namespace std;
class Circle {
public:
void operation(){
cout<<"Drawing...";
}
};
class Circle: public Shape
{
public:
void operation()
{
cout<<"Drawing Something...";
}
};
int main(void) {
Circle c = Circle();
c.operation();
return 0;
}
Output:
Drawing Something...
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 17,2021