Site icon DataFlair

Polymorphism in C++ The Essential Guide

Polymorphism in C++

Free C++ course with real-time projects Start Now!!

Polymorphism in C++  is basically the ability for data to be processed or represented in more than one form. It is one of the most important concepts of object-oriented programming. To get well acquainted with the concept we’re going to discuss its subtopics along with some real-life examples and codes too.

Polymorphism in C++

C++ Polymorphism is a salient feature of object-oriented programming. Without polymorphism, a programming language cannot be recognized as an object-oriented language, even if it supports all the features like abstraction, encapsulation, inheritance, and data hiding.

Key takeaway: Programming languages that support classes and objects but not polymorphism is “object-based” languages. For example, VB (Visual Basic)

Polymorphism allows the data in the form of a message or a group of statements when executed to behave differently in different scenarios.

Let us consider a real-life problem in order to better understand the meaning of polymorphism.

For example, you are a student of class 12th A of 40 students. You are similar to other students in your class with respect to the subjects and teachers assigned. If we get the message -“Students of class 12th A kindly come to the auditorium”, all the 40 students would assemble in the auditorium.

But, if we get a different message – “Students of class 12th A, who are the discipline in-charges of the class, kindly come to the auditorium”, then only a handful of students out of the 60 students would assemble in the auditorium. This difference in behavior according to the message conveyed despite there being similarities in properties is called polymorphism.

Types of Polymorphism in C++

Polymorphism in C++ can be classified into two types:

1. Compile-time polymorphism: We can achieve this type of polymorphism only during compilation. We can implement this type of polymorphism through function overloading and operator overloading, an exclusive feature of C++. Since function overloading and operator overloading is based on the type and number of the parameter passed, the compiler chooses the appropriate function call at compile-time.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

2. Runtime polymorphism: We can achieve this type of polymorphism only during the runtime of the program. It is also known as function overriding, dynamic binding, and late binding. In order to achieve runtime polymorphism, we use the concept of virtual functions which is based on pointers. In contrast to compile-time polymorphism, it is a tad slower but proves to be more flexible.

Here is a code that illustrates runtime polymorphism through function overriding:

#include <iostream>
using namespace std;
class base 
{
public:
void display()
{
cout<<"This is a base class function\n"<<endl;
}
};
class derived: public base
{
public:
void display()
{
cout<<"This is a derived class function\n";
}
};
int main() 
{

printf("Welcome to DataFlair tutorials!\n\n");

base b; // creating object b of base class 
b.display();

derived d; //creating object d of derived class
d.display();

return 0;
}

Output-

Implementation of Polymorphism in C++

As we have our discussion that polymorphism is an attribute that allows us to use a single interface differently in different situations. Keeping this in mind, let us discuss the ways in which we can implement polymorphism in C++.

The most popular way to implement polymorphism is through a hierarchy of classes, overloaded functions, operators, and virtual function in C++.

We use the virtual function to define the interface as an abstract class, although its implementation details are made available by the concrete classes.

Polymorphism Vs Function Overloading in C++

Most people consider function overloading is a way to implement polymorphism. It is important to note that is it not true. It is just a throwaway statement that people have implanted in their minds without even thinking about evidence that supports this statement.

Polymorphism and function overloading are both two different concepts that cannot be sub-categorized into another. Although they are related to each other, they aren’t similar.

Let us first try to understand what is function overloading.

Function overloading is simply a feature in C++ where more than one function can share the same name but have different arguments/parameters.

Here is a table that would help you differentiate between Polymorphism and Function Overloading in C++-

Polymorphism
Function Overloading
Polymorphism associated with objects.
The function overloading associated with function call methods.
It helps you to subclass different types of objects.
It helps you implement variations in instructions.

This diagram will help you better understand the relationship between polymorphism and function overloading:

Significance of Virtual Functions in C++

The discussion on polymorphism is incomplete without explaining the significance of virtual functions. As discussed earlier, virtual functions are a way to implement runtime polymorphism. Here, we call the derived class function with the help of a base class pointer.

Here is a program that illustrates the use of virtual functions in C++:

#include<iostream> 
using namespace std; 

class Base 
{ 
public: 
virtual void display() 
{
cout<<"I am a Base Class"<<endl;
} 
}; 

class Derived: public Base 
{ 
public: 
void display() 
{
cout<<"I am a Derived Class \n"; } 
}; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Base *p = new Derived; 
p->display(); // Envoked suring runtime 
return 0; 
} 

 

Output-

Quiz on Polymorphism in C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    What is the output of following program?

    #include <bits/stdc++.h>

      

    using namespace std;

    class A

    {

        public:

        void print(int x)

        {

            cout <<x << endl;

        }

        void print(double x)

        {

            cout << x << endl;

        }

    };

      

    int main() {

          

        A obj;

     

        obj.print(7.0);

        return 0;

     

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    What is the output of following program?

    #include <bits/stdc++.h>

      

    using namespace std;

    class A

    {

        public:

        void print(int x)

        {

            cout <<x << endl;

        }

        void print(double x)

        {

            cout << x << endl;

        }

    };

      

    int main() {

          

        A obj;

     

        obj.print(7.098);

        return 0;

     

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    What is the output of following program?

    #include <bits/stdc++.h>

      

    using namespace std;

    class A

    {

        public:

        void print(int x, int y)

        {

            cout <<x <<” “;

        }

        void print(int x)

        {

            cout << x <<” “;

        }

    };

      

    int main() {

          

        A obj;

        obj.print(7);

        obj.print(8,9);

        return 0;

     

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    What is the output of following program?

    #include<iostream>

    using namespace std;

       

    class A {

    private:

        int a, b;

    public:

        A(int x = 0, int y =0)  {a = x;   b = y;}

     

        A operator + (A const &obj) {

             cout<<obj.a;

        }

    };

       

    int main()

    {

        A O1(1, 2), O2(3, 6);

        A O3 = O1 + O2; 

    }

     

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    What is the output of following program?

    #include<iostream>

    using namespace std;

       

    class A {

    private:

        int a, b;

    public:

        A(int x = 0, int y =0)  {a = x;   b = y;}

     

        A operator + (A const &obj) {

             cout<<b;

        }

    };

       

    int main()

    {

        A O1(1, 2), O2(3, 6);

        A O3 = O1 + O2; 

    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    What is the output of following program?

    #include<iostream>

    using namespace std;

       

    class A {

    private:

        int a, b;

    public:

        A(int x = 0, int y =0)  {a = x;   b = y;}

     

        A operator + (A const &obj) {

             A i;

             i.b=obj.b;

             cout<<i.b;

        }

    };

       

    int main()

    {

        A O1(1, 2), O2(3, 6);

        A O3 = O1 + O2; 

    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    What is the output of following program?

    class A {

    private:

        int a, b;

    public:

        A(int x = 0, int y =0)  {a = x;   b = y;}

     

        A operator + (A const &obj) {

             A i;

             i.a = a +obj.a;

             i.b = b + obj.b;

             return i;

        }

        void show() { cout << a << ” “<< b << endl; }

    };

       

    int main()

    {

        A O1(1, 2), O2(3, 6);

        A O3 = O1 + O2; 

        O3.show();

    }

     

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    What is the following program?

    #include <bits/stdc++.h>

    using namespace std;

      

    class b

    {

    public:

        virtual void Display ()

        { cout<< “B” <<endl; }

    };

       

    class d:public b

    {

    public:

        void Display () 

        { cout<< “D” <<endl; }

    };

      

    int main() 

    {

        b *bptr;

        d d1;

        bptr = &d1;

        bptr->Display();

        return 0;

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    What is the output of following program?

    #include <bits/stdc++.h>

    using namespace std;

      

    class b

    {

    public:

        void Display ()

        { cout<< “B” <<endl; }

    };

       

    class d:public b

    {

    public:

        void Display () 

        { cout<< “D” <<endl; }

    };

      

    int main() 

    {

        b *bptr;

        d d1;

        bptr = &d1;

        bptr->Display();

        return 0;

    }

     

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    What is the output of following program?

    #include <bits/stdc++.h>

    using namespace std;

      

    class b

    {

    public:

        void Display ()

        { cout<< “B” <<endl; }

    };

       

    class d:public b

    {

    public:

        virtual void Display () 

        { cout<< “D” <<endl; }

    };

      

    int main() 

    {

        b *bptr;

        d d1;

        bptr = &d1;

        bptr->Display();

        return 0;

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

     Which among the following does not fall under polymorphism?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Which among the following does not fall under Compile time polymorphism?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    When a derived class have definition of one of the member function of base class is called

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    When there are multiple Functions with same name but different parameters is called

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    Virtual function operation is referred as

    Correct
    Incorrect

Summary

Polymorphism is a key element to master in order to get a command over C++. Beginners should be well equipped with this skill. Function overloading is a subset of polymorphism, not entirely polymorphism itself. The diagram which we discussed, is again a very important concept in C++ as well as other object-oriented programming languages. The core concept of Polymorphism is the same in all programming languages, the only difference arises in its syntax and ways to implement it.

Exit mobile version