Explain the type of polymorphism with code
// C++ program to demonstrate compile polymorphism using method overloading and run time polymorphism using method overriding
#include <iostream>
using namespace std;
//C++ compile time polymorphism using method overloading
class CTPolymorphism
{
public:
void add(int x, int y)
{
cout<<"The sum of x and y is : "<<x + y<<endl;
}
void add( double a, double b)
{
cout<<"The sum of x and y is : "<<a + b<<endl;
}
};
//C++ runtime poloymorphism using method overriding
class RTPolymophismParent
{
public:
void greet()
{
cout<<"Greetings from parent greet() method class"<<endl;
}
};
//inherits parent
class RTPolymophismChild: public RTPolymophismParent
{
public:
void greet() //greet() method has been overridden by child class
{
cout<<"Greetings from child greet() method"<<endl;
}
};
//Driver code
int main()
{
//Compile time section
CTPolymorphism compileTime;
compileTime.add(30, 50); //Calls add with int params
compileTime.add(34.2, 60.9);//Calls add with double params
//Run time section
RTPolymophismChild runTime;
runTime.greet(); //This will call child class greet()
return 0;
}
Comments
Leave a comment