Polymorphism is
one of the crucial features of OOP. It simply means ‘one name, multiple forms’. We have already seen how the concept of polymorphism is implemented using the overloaded functions and operators.
Mainly
they are two types of polymorphism.
Types of
Polymorphism in C++:
Compile time polymorphism:
The overloaded member functions are ‘selected’ for
invoking by matching arguments, both type and number. This information if known
to the compiler at the compile time and, therefore, compiler is able to select
the appropriate function for a particular call at the compile time itself. This
is called early binding or static binding. Also
known as compile time polymorphism, early
binding means that an object is bound to its function call at compile time.
Run time polymorphism:
Binding in C++:
class Base //base
{
int b;
public:
void display( )
//base member function
{
}
};
class
Derived: public Base //derived
{
int d;
public:
void display( ) //derived member function
{
}
};
How do we use the member function display( ) to display the values of
objects of both the classes Base and
Derived?. Since the prototype of display( ) is the same in both the
places, the function is not overloaded and therefore static binding does not
apply. We have seen earlier that, in such situations, we may use the class resolution operator to specify
the class while invoking the functions with the derived class objects.
It would be nice if the appropriate
member function could be selected while the program is running. This is known
as run time polymorphism. How could
it happen?
C++ supports a mechanism known as virtual function to achieve run time polymorphism.
At
run time, when it is known what class objects are under consideration, the
appropriate version of the function is invoked. Since the function is invoked
with a particular class much later after the compilation, this process is termed
as late binding. It is also known as
dunamic binding because the
selection of the appropriate function is done dynamically at run time.
Dynamic Binding is one of the powerful
features of C++. This requires the use of pointers to objects. We shall discuss
in detail how the object pointers and virtual
functions are used to implement dynamic
binding.
0 comments:
Post a Comment