Skip to main content
Engineering LibreTexts

15.1: Polymorphism

  • Page ID
    45682
  • Polymorphism in C++

    The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
    For instance, a real life example of polymorphism would be a man who can be a father, a husband, an employee all at the same moment in time. So the same person posses different behavior in different situations. This is called polymorphism.

    Polymorphism is considered as one of the important features of Object Oriented Programming.

    In C++ polymorphism is mainly divided into two types:

    • Compile time Polymorphism
    • Runtime Polymorphism

    1. Compile time polymorphism: This type of polymorphism is achieved by method overloading or operator overloading.
      // C++ program for method overloading
      #include <iostream>
      
      
      using namespace std;
      class CSP31
      {
          public:
          
              // method with 1 int parameter
              void outFunc(int x)
              {
                  cout << "value of x is " << x << endl;
              }
          
              // method with same name but 1 double parameter
              void outFunc(double x)
              {
                  cout << "value of x is " << x << endl;
              }
              
              // method with same name and 2 int parameters
              void outFunc(int x, int y)
              {
                  cout << "value of x and y is " << x << ", " << y << endl;
              }
      };
      
      
      int main() 
      {
          CSP31 myObj1;
          
          // Which method is called will depend on the parameters passed
          // The first 'outFunc' is called
          myObj1.outFunc(7);
          
          // The second 'outFunc' is called
          myObj1.outFunc(9.132);
          
          // The third 'outFunc' is called
          myObj1.outFunc(85,64);
          return 0;
      }
      

       

    In the above example, a single method named outFunc() acts differently in three different situations which is the property of polymorphism.

    Method Overloading: When there are multiple methods with same name but different parameters then these methods are said to be overloaded. methods can be overloaded by change in number of arguments or/and change in type of arguments.

    The output of the above code is:

    value of x is 7
    value of x is 9.132
    value of x and y is 85, 64
    

    Operator Overloading: C++ also provide option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add two operands. So a single operator ‘+’ when placed between integer operands , adds them and when placed between string operands, concatenates them.

    // CPP program to illustrate
    // Operator Overloading
    #include<iostream>
    using namespace std;
    
    class Complex {
        private:
            int real, imag;
        public:
            Complex(int r = 0, int i =0)
            {
                real = r; imag = i;
            }
            
            // This is automatically called when '+' is used with
            // between two Complex objects
            Complex operator + (Complex const &obj)
            {
                Complex res;
                res.real = real + obj.real;
                res.imag = imag + obj.imag;
                return res;
            }
            void print()
            {
                cout << real << " + i" << imag << endl;
            }
    };
    
    
    int main()
    {
        Complex c1(10, 5), c2(2, 4);
        Complex c3 = c1 + c2; // An example call to "operator+"
        c3.print();
    }
    
    
    

    In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition operator and can add two numbers(integers or floating point) but here the operator is made to perform addition of two imaginary or complex numbers. Notice that in the '+' method there is a keyword "operator" - this is required whenever you are overloading one of the C++ mathematical operators.

    The output from the above code is below. If you do not understand real and imaginary numbers don't worry - we will not be delving into that topic in this course.

    12 + i9
    

     

    1. Runtime polymorphism: This type of polymorphism is achieved by method Overriding.
      • Method overriding occurs when a derived class has a definition for one of the member methods of the base class. That base method is said to be overridden.
    // C++ program for method overriding
    #include <iostream>
    using namespace std;
    
    class base
    {
        public:
            virtual void print ()
            {
                cout<< "print base class" <<endl;
            }
    
            void show ()
            {
                cout<< "show base class" <<endl;
            }
    };
    
    
    class derived:public base
    {
        public:
            //print () is already virtual method in derived class
            // we could also declared as virtual void print () explicitly
            void print ()  
            {
                cout<< "print derived class" <<endl;
            }
    
            void show ()
            {
                cout<< "show derived class" <<endl;
            }
    };
    
    
    //main method
    int main()
    {
        base *bptr;
        derived deriv;
        // Assigne the address of the derived class instance
        bptr = &deriv;
        
        // print() is a virtual method in the parent class
        // bound at runtime (Runtime polymorphism)
        bptr->print();
        
        // show() is a non-virtual method in the parent class
        // bound at compile time
        bptr->show();
    
    
        return 0;
    }
    
    

    Output:

    print derived class
    show base class
    

    Inheritance and Polymorphism.

    There are some differences between Inheritance and Polymorphism shown in the table below

      INHERITANCE POLYMORPHISM
    1. Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms.
    2. It is basically applied to classes. Whereas it is basically applied to functions or methods.
    3. Inheritance supports the concept of reusability and reduces code length in object-oriented programming. Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding).
    4. Inheritance can be single, hybrid, multiple, hierarchical and multilevel inheritance. Whereas it can be compiled-time polymorphism (overload) as well as run-time polymorphism (overriding).
    5. It is used in pattern designing. While it is also used in pattern designing.

    Adapted from:
    "Polymorphism in C++" by Harsh AgarwalGeeks for Geeks
    "Difference between Inheritance and Polymorphism" by MKS075, Geeks for Geeks

    • Was this article helpful?