DEFINITION 16: POLYMORPHISM - PRATMG/2143-OOP-Tamang GitHub Wiki

The term polymorphism refers to the presence of multiple forms. Polymorphism is defined as the ability of a message to be displayed in more than one form. A person can have multiple characteristics at the same time, which is an example of polymorphism in action. A man is a father, a husband, and an employee all at the same time. As a result, the same person exhibits different behavior in different situations. This is known as polymorphism. Polymorphism is regarded as an important aspect of Object Oriented Programming.

There are two types of Polymorphism in C++:

  • Compile time Polymorphism
  • Runtime Polymorphism

poly

Compile time Polymorphism:

Static binding or early binding are terms used to describe compile time polymorphism. It occurs throughout the compilation process. To achieve compile-time polymorphism, we use function and operator overloading.

Function Overloading Operator Overloading
Function overloading occurs when two or more functions in C++ have the same name but differ in the number and/or type of parameters. Overloaded functions are those with the same name but different parameters. In C++, we can also overload operators. For user-defined types such as objects and structures, we can modify the behavior of operators.

Runtime Polymorphism:

Function Overriding is used to achieve runtime polymorphism. Function overriding, occurs when a derived class defines one of the base class's member functions. Overriding refers to the act of overriding a base function.

// C++ program for function overriding

#include <bits/stdc++.h>
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;
}

Reference: