Polymorphism: Real Life Example of Polymorphism
Polymorphism: Real Life Example of Polymorphism
Polymorphism: Real Life Example of Polymorphism
int main() {
Geeks obj1;
// Which function is called will depend on the parameters passed
// The first 'func' is called
obj1.func (7);
// The second 'func' is called
obj1.func (9.132);
// The third 'func' is called
obj1.func (85, 64);
return 0;
}
Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64
Operator Overloading: C++ also provide option to overload operators. For
example, we can make the operator (‘+’) for string class to concatenate two strings.
We know that this is the addition operator whose task is to add two operands. So a
single operator ‘+’ when placed between integer operands, adds them and when
placed between string operands, concatenates them.
Runtime polymorphism: This type of polymorphism is achieved by Function
Overriding.
Function overriding occurs When child class declares a method, which is already
present in the parent class then this is called function overriding.
// C++ program for function overriding
#include <iostream>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived: public base
{
public:
void print () //print () is already virtual function in derived class, we could also
declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime (Runtime polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Output:
print derived class
show base class