In object oriented programming, polymorphism is a concept that can process the objects differently with respect to the data type or the class of the objects. Polymorphism redefines the methods for derived classes or child classes.
Polymorphism is used in class inheritance. That is this concept is applied to base classes and derived classes. You should have a basic knowledge of pointers to understand polymorphism. Let us look at a simple example:
Here shape is the base class and circle, triangle and square are derived classes. Now we are introducing early binding and late binding.
Binding is a process, that is used to convert the variable names and function names into machine. There are two types of binding in C++ programming language; early binding and late binding. Early binding means that the compiler is able to convert the variable names and functions names into machine language address directly.
All the functions have a different address in machine language; therefore, the compiler directly goes to that function. The direct function call is solved by early binding.
Late binding is also called dynamic binding. In C++ programming language dynamic means at run time. It means that when it is not possible for the compiler to run a program or to know which function is to be call until run time, this is known as late binding. In C++ programming, to get late binding, we use function pointers.
A function pointer refers to a pointer that point to function instead of variables. Consider the following example to understand the concept of late binding:
A virtual function is a function that is declared in the base class. It is declared using a keyword virtual. A virtual function that is defined in the base class and has some versions in the derived class too tells the compiler that there is no need to add a static linkage for this function.
We only need to call the function anywhere or any point in the program. Consider the following example.
# include <iostream>
using namespace std;
# include <conio.h>
virtual void show ();
void base :: show ( )
cout << ”base class” ;
class derived: public base
void show ();
void derived :: show ()
cout << ”derived class” ;
void main ()
base *b = new d;
b -> show ();
Working of above program:
In the main function, pointer is used to call the function show () through late binding. As we are using a pointer, we use the dereferencing operator (->) to call the function. The function is called using the base class pointer. In the line base *b =new d; the pointer b contains the address of object of derived class that is d. Therefore the function show () of derived class is called and it prints: