Mechanism for polymorphism in c++
Answers
Answered by
0
Polymorphism as the name itself suggests is a feature of C++ which allows representation of the same entity in more than one forms.
In C++ polymorphism can be attained in following ways:
1. Function Overloading
2.Operator Overloading
3. Constructor Overloading
Eg:1.
int sum(int a, int b)
{ return(a+b); }
int sum(int a, int b, int c)
{ return(a+b+c); }
int main()
{
int a=2,b=5,c=8;
cout<<sum(a,b); // Output will be 7; and 1st sum function with two parameters will be called.
cout<<sum(a,b,c); // Output will be 15; and 2nd sum function with 3 parameter will be called.
return(0);
}
Eg: 2.
class example
{
int a;
public:
example()
{
cout<<"Enter a number:";
cin>>a;
}
example(int x)
{
a=x;
}
};
int main()
{
int m=5;
example e; // 1st constructor with no parameter will be called.
example f(m); //2nd constructor with 1 parameter will be called.
return 0;
}
In C++ polymorphism can be attained in following ways:
1. Function Overloading
2.Operator Overloading
3. Constructor Overloading
Eg:1.
int sum(int a, int b)
{ return(a+b); }
int sum(int a, int b, int c)
{ return(a+b+c); }
int main()
{
int a=2,b=5,c=8;
cout<<sum(a,b); // Output will be 7; and 1st sum function with two parameters will be called.
cout<<sum(a,b,c); // Output will be 15; and 2nd sum function with 3 parameter will be called.
return(0);
}
Eg: 2.
class example
{
int a;
public:
example()
{
cout<<"Enter a number:";
cin>>a;
}
example(int x)
{
a=x;
}
};
int main()
{
int m=5;
example e; // 1st constructor with no parameter will be called.
example f(m); //2nd constructor with 1 parameter will be called.
return 0;
}
Similar questions