Topic :Polymorphism: Compile-Time Polymorphism. | Run-Time Polymorphism. | Overloading | Overriding

What is Polymorphism:

Polymorphism is key to the power of Object-Oriented-Programming (OOP). it's so Important that languages that don't support Polymorphism can't advertise themselves as OO languages. Languages that support classes but not polymorphism are called Object-Based Languages.

Polymorphism comes from Greek word, meaning "Many Forms". It is the Quality that allows one interface to access a General class of Actions. A simple Example of Polymorphism is found in the Steering Wheel of an Automobile. The Steering wheel ( The Interface) is the same no matter what type of actual Steering Mechanism is used. That is, the steering wheel works the same whether our car has manual steering, power steering, or rack-and-pinion steering. Thus, turning the steering wheel left causes the car to go left no matter what type of steering is used. The benefit of the uniform interface is, of course, that once we know how to operate the steering wheel, we can drive any type of car.



image: Polymorphism

The Concept of Polymorphism was first identified by Christopher Strachey in 1967. Later, developed by Hindley and Milner. It is not important to understand how polymorphism is implemented but how it works. C++ Offers two ways to retrieve the type of objects and expressions while the program is running, at compile time and Runtime. the basic idea behind Polymorphism is that the compiler does not know which function to call at compile time. This is done at runtime. The term Polymorphism refers to the fact that it is used in OOP that the decision to be used will not be known at compiler time. The decision to be postponed until the program is actually executed which respond to the runtime. The runtime is referred to late binding. Polymorphism is realized by this feature.



C++ Polymorphism:

The word Polymorphism means having many forms. Typically, Polymorphism occurs when there is a Hierarchy of Classes and they are related by inheritance. C++ Polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

Consider the following example where a base class has been derived by other two classes ( Hierarchical Inheritance )

/* Polymorphism Example: InfoBrother */
 
#include <iostream>
using namespace std;
 
class Shape //base class.
{
    protected:
        int width, height;
 
    public:
        Shape( int a=0, int b=0) //Constructor.
         {
            width = a;
            height = b;
         }
 
        int area() //Simple Function to display the result.
         {
            cout << "Shape class area | Base Class | :" <<endl;
            return 0;
         }
};
 
class Rectangle: public Shape //Derived Class from the Class shape.
{
    public:
        Rectangle( int a=0, int b=0):Shape(a, b) { } //constructor.
        int area () //Simple function to display result.
        {
            cout << "Rectangle class area | Derived Class | :" <<endl;
            return (width * height);
        }
};
 
class Triangle: public Shape //Derived Class from class Shape.
{
    public:
        Triangle( int a=0, int b=0):Shape(a, b) { } //Constructor.
        int area () //Simple function to display result.
         {
            cout << "Triangle class area | Derived Class | :" <<endl;
            return (width * height / 2);
         }
};
 
 
int main( )
{
    Shape *shape;        //pointer Object of type shape.
    Rectangle rec(10,7); //Rectangle Object.
    Triangle tri(10,5);  //Triangle Object.
 
 
    shape = &rec;   // store the address of Rectangle
    shape->area();  // call rectangle area using this pointer.
 
    shape = &tri;  // store the address of Triangle
    shape->area(); // call triangle area using this pointer.
 
    return 0;
}


In above example, we used an operator -> to call function in main program. This operator in know as This Pointer. we will discuss about such pointer in our "Pointer to Object" tutorials.


The Output is incorrect, We didn't supposed to get this output from this program. The reason for the incorrect output is that the call of function area() is being set once by the compiler as the version defined in the base class. This is called Static resolution of the function call. The function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program.

But now, let's make a slight modification in our program and precede the declaration of area() in the Shape Class with the keyword Virtual so that it looks like this:


/* Polymorphism Example: InfoBrother */
 
#include <iostream>
using namespace std;
 
class Shape //base class.
{
    protected:
        int width, height;
 
    public:
        Shape( int a=0, int b=0) //Constructor.
         {
            width = a;
            height = b;
         }
 
         virtual int area() //Simple Function to display the result.
         {
            cout << "Shape class area | Base Class | :" <<endl;
            return 0;
         }
};
 
class Rectangle: public Shape //Derived Class from the Class shape.
{
    public:
        Rectangle( int a=0, int b=0):Shape(a, b) { } //constructor.
        int area () //Simple function to display result.
         {
            cout << "Rectangle class area | Derived Class | :" <<endl;
            return (width * height);
         }
};
 
 
class Triangle: public Shape //Derived Class from class Shape.
{
    public:
        Triangle( int a=0, int b=0):Shape(a, b) { } //Constructor.
        int area () //Simple function to display result.
         {
            cout << "Triangle class area | Derived Class | :" <<endl;
            return (width * height / 2);
         }
};
 
 
int main( )
{
    Shape *shape; //pointer Object of type shape.
    Rectangle rec(10,7); //Rectangle Object.
    Triangle tri(10,5); //Triangle Object.
 
 
    shape = &rec;     // store the address of Rectangle
    shape->area(); // call rectangle area using this pointer.
 
    shape = &tri; // store the address of Triangle
    shape->area(); // call triangle area using this pointer.
    return 0;
}



That Exactly what we need, this time, the compiler looks at the contents of the pointer instead of its type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called.



As we can see, each of the child classes or derived classes have a separate implementation for the function area(). This is how Polymorphism is generally used. we have different classes with a function of the same name and even the same parameters, but with different implementations.





Compile-Time Polymorphism:

The compiler is able to select the appropriate function for a particular call at compile-time itself. This is known as compiler-time polymorphism.

In C++ Programming we can achieve compile time polymorphism in two ways, which is given below.




Method Overloading:

Whenever same Method name is existing Multiple times in the same class with different number of parameter or different order of parameters or different types of parameters is known as Method Overloading.


  • Ways to Overload a Method:

    » By Changing Number of Arguments.
    » By Having Different types of Arguments.



Let's have an simple Example of Overloading. In this Example we will overload the method by changing Numbers of Arguments:

/*Method Overloading Example: InfoBrother*/
 
#include<iostream>
using namespace std;
 
class math //class.
{
 
    public:
        void result(int x, int y) //Method to show result.
        {
            cout<<" The result is : "<<x+y;
        }
 
        void result(int x, int y, int z) //Method overloading with extra parameter.
        {
         cout<<" The result is: "<<x+y+z;
        }
};
 
main()
{
    math obj; //Object of type math.
 
    obj.result(10,15); //1st method Called.
    cout<<endl;
 
    obj.result(10,5,15); //overload method called.
    return 0;    
}

In the above simple example we just overload an simple Method, result() with some extra parameters. We will discuss more about Function or Method Overloading in our Function Overloading Tutorial.




Method Overriding:

If we inherit a class into the derived class and provide a definition for one of the base class's Method again inside the derived class, then that Method is said to be overridden, and this mechanism is known as Method Overriding

  • Requirements for Overriding:

    » Inheritance should be there. Function Overriding cannot be done within a class. For this we require a derived class and a base class.
    » Function that is redefined must have exactly the same declaration in both base and derived class, that means same name, same return type, and same parameter list.


Let's have an Example of Method Overriding:


/*Method Overriding Example: InfoBrother*/
 
#include<iostream>
using namespace std;
 
class base //base class.
{
    public:
        void output() //simple method to print something.
        {
            cout<<" Its Base Class: "<<endl;
        }
};
 
class derived: public base //derived a class from class base.
{
    public:
        void output() //overridden method.
        {
            cout<<" Its Derived Class: "<<endl;
        }
};
 
main()
{
    base parent;   //object of type base.
    derived child; //Object of type derived.
 
    parent.output();   //1st method called.
    cout<<endl;
 
    child.output();   //overridden method called.
 
    return 0;    
}


Run-Time Polymorphism:

Run time Polymorphism is achieving which object's method should invoke during Runtime instead of compile time. For instance, we have two classes B and C derived from a Base class A. and we create a pointer to the class A and make it point to any of the derived class objects. and when we call a method using that pointer, the corresponding derived class method is called instead of the base class method. We Need to put the base class method as Virtual for this to work.



We will discuss about "Virtual Method" in our Virtual Function Tutorial.

Read more about Virtual Function in C++.












I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement