Polymorphism in C++ by R4R Team

What polymorphism word means?
-The word polymorphism means having many forms.
or
-we can define polymorphism as the ability of a message to be displayed in more than one form.

Basically, polymorphism have two forms:
-compile time polymorphism(static polymorphism)
-run time polymorphism(dynamic polymorpohism)

Compile time polymorphism:

Example of compile time polymorphism is:
-Function overloading
-Operator overloading

Run time overloading:
Example of run time polymorphism is:
-Function overriding

Function overloading:
Function overloading is a feature in C++ where two or more functions can have the same name but different parameters.

program:

#include < iostream>

using namespace std;
class r4r
{
public:
int sum(int a,int b, int c)
{
cout<<"Sum is: "<< a+b+c<< endl;
}
int sum(int a,int b)
{
cout<<"Sum is: "<< a+b<< endl;
}
int sum(double a,double b)
{
cout<<"Sum is: "<< a+b<< endl;
}
};

int main()
{
r4r obj;
obj.sum(2,3,4);
obj.sum(1,2);
obj.sum(3.2,4.1);
return 0;
}


output-

Sum is: 9
Sum is: 3
Sum is: 7.3


Function overriding:
If derived class defines same function as defined in its base class, it is known as function overriding in C++.

program:

#include < iostream>
using namespace std;
class parent {
public:
void func(){
cout<<"This is my parent function";
}
};
class child: public parent
{
public:
void func()
{
cout<<"Child function";
}
};
int main(void) {
child d = child();
d.func();
return 0;
}


output-

Child function




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!