Explain the type of polymorphism with code.
/*
C++ Supports two main types of polymorphism. Runtime and compile time polymorphism.
Compile time can be accomplished using:
-Method overloading and
-Operator overloading.
in this example we are going to use method overloading.
Runtime polymorphism can be implemented using:
-Method overriding and
-Virtual functions
in this example we will use method overriding to demonstrate
*/
#include <iostream>
using namespace std;
//Compile time polymorphism
class CompileTime
{
public:
void display(int x)
{
cout<<"The int is : "<<x<<endl;
}
void display( char ch)
{
cout<<"The character is : "<<ch<<endl;
}
};
//Runtime polymorphism section
class RuntimeParent
{
public:
void sayHello()
{
cout<<"Hello from parent"<<endl;
}
};
class RuntimeChild: public RuntimeParent
{
public:
void sayHello() //Method with same name as parent method. This has been overridden.
{
cout<<"Hello from child"<<endl;
}
};
int main()
{
//Compile time polymorphism using method overloading
CompileTime ct;
ct.display(5);
ct.display('x');
//Runtime polymorphism using method overriding
RuntimeChild rc;
rc.sayHello(); //This will call child class sayHello()
return 0;
}
Comments
Leave a comment