Google

Polymorphism in C++

Written on:May 8, 2013
Comments are closed




Polymorphism in C++

Polymorphism refers to “One Object Many Forms”. It is one of the most important features of OOPs. Polymorphism is implemented through Overloaded operators and Overloaded functions. Polymorphism can be compile time polymorphism or runtime polymorphism. In C++, polymorphism is implemented through virtual functions and dynamic binding. Early binding refers that an object is bound to its functions call at compile time. Compile time polymorphism is achieved through overloaded functions. The overloaded member functions are invoked as per their argument type and number.  For example:

int simple_interest (int principal, int rate, int time);
float simple interest (float principal, float rate, float time);

The following function call:
simple_interest (1000,5);//invokes first  prototype

Whereas the function call
simple_interest(2000,50,2.50,4.50); //Invokes the second prototype

This information is available during compile time to which function will be invoked with respect to a function call.

Run-time polymorphism is achieved through virtual functions.

For example:

class B
{
public:
virtual void func1();
}

class D : public B
{
public:
void func1();
}

void B : : func1()
{
cout<<”control in base class —-?”;
}

void D : : func1()
{
cout<<”control in derived class—–?”;
}
void main()
{
B b_obj; D d_ojj;
B *b_ptr;
b_ptr = &b_obj;
b_ptr->func1();
b_ptr = &d_obj;
b_ptr->func1();
}

If Base class function is not defined as virtual then the base class pointer always invokes the base class function irrespective of the object being pointed to by the base class pointer. But when the base class function is defined as virtual, then it is determined at run time as to invoke which function and hence is runtime polymorphism.

 

Sorry, the comment form is closed at this time.