C++
Important Links
What is polymorphism?
Polymorphism is a mechanism in which Having more than one method with the same name but behavior is different is called polymorphism. In other words, an ability to access one or more method by using single interface (name) is called polymorphism.
The word polymorphism means having many forms.
Types of polymorphism :-
There are two types of polymorphism in C++:
Example :-
Method and constructor overloading is example of compile time polymorphism.
Method overriding is example of runtime polymorphism.
Note :-
Note :- compile time means compiler check the method is defined or not in compile time. If method is defined correctly then true otherwise compile time error.
Runtime :- here method is checked at run time means. Here compiler doesnot check the method is defined or not at complie time. If method is not defined then run time error occurs.
compile Time polymorphism :-
If we create two or more members having same name but different in number or type of parameter, it is known as overloading.
Types of overloading :-
Function Overloading :-
Function Overloading (method overloading): If a class have multiple methods by same name but parameters are different is called method overloading.
Having two or more function with same name but different in parameters, is known as function overloading in C++.
The advantage of Function overloading is that it increases the readability of the program because you don't need to use different names for same action.
Function Overloading Example :-
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C;
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output :-
55
Operators Overloading :-
Operator overloading is used to overload or redefine most of the operators available in C++. It is used to perform operation on user define data type.
The advantage of Operators overloading is to perform different operations on the same operand.
operator Overloading Example :-
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
Output :-
runtime polymorphism :-
runtime polymorphism Example :-
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}