Runtime Polymorphism - OOPs Concept in C++

How is Runtime Polymorphism used in OOPs concept of C++?

Explanation

Runtime Polymorphism is a form of polymorphism at which function binding occurs at runtime.


You can have a parameter in subclass, same as the parameters in its super classes with the same name. Virtual keyword is used in superclass to call the subclass. The function call takes place on the run time, not on the compile time.

Example :






#include <iostream.h>
Class Shape
{
public:
virtual void area()
{
cout << "Base class area Calculation"
}

};


Class Square : public Shape
{
public:
void area()
{
cout << "Derived class area Calculation"
}

}

int main()
{
Shape* sp;
Square sq;
sp=&sq;
sp->area();
}




Result :

Derived class area Calculation


In the above example, square is the super class and shape is the sub class of area. Here virtual keyword indicates the member function of the shape super class. If you call member function, binding occurs on run time only.

C++ Tutorial


Ask Questions

Ask Question