Polymorphism in C++: Understanding the Concept and Its Types

Updated on October 10, 2024

Article Outline

Polymorphism is an object-oriented concept where an object can take on different forms. It is of two types: compile-time and run-time polymorphism. It enhances code readability, reusability, and maintainability, speeds up the code, and reduces memory space. Let’s do a deep dive and understand the polymorphism in C++ in detail.

What is Polymorphism in C++?

Polymorphism is an object-oriented concept where an object can take on different forms and behaviours. It can be achieved through function overloading, function overriding, inheritance, and virtual functions. It enhances code reusability, flexibility, and extensibility. It is an important tool to create well-designed and maintainable programs.

 

Let’s discuss a real-life example of polymorphism. Suppose you go to a grocery shop and buy different kinds of fruits like apples, oranges, bananas, etc. Each of these fruits has different characteristics, but all are grouped under the category of “fruit.” This is the perfect example of polymorphism, where different objects are grouped under a single name.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Types of Polymorphism in C++

On the basis of functionality, polymorphism can be divided into two types:

 

  • Compile Time Polymorphism: In compile time polymorphism, the relationship between the definition of different functions and their calls is identified at compile time. It is commonly known as static or early-binding polymorphism. It can be implemented through function and operator overloading. It offers less flexibility to the developers as everything is executed during compilation. It has a much faster execution rate; however, it is less preferred for handling complex problems.

 

  • Runtime Polymorphism: In runtime polymorphism, the compiler resolves an object at runtime and determines which function call will be associated with that object. It is commonly known as dynamic or late-binding polymorphism. It offers more flexibility as everything is executed during run-time. Although it has a comparatively slow execution rate, it is better at handling complex problems.

Ways to Implement Compile-Time Polymorphism in C++

In C++, we can implement compile-time polymorphism in two ways.

Function Overloading

The ability to declare multiple functions with the same name but different types and orders of parameters is known as function overloading. It is a special feature of OOPS and is based on the idea of polymorphism. It can take place in both the base class and the derived class. All the overloaded functions share the same scope.

 

Example:

// Example of function overloading # include<bits/stdc++.h> using namespace std; // Define overloaded function signatures. void productOfNumber(int p, int q); void productOfNumber(int p, int q, int r); void productOfNumber(int p, int q, int r, int s); int main() { // Calling the overloaded functions with different number of arguments productOfNumber(11,20); productOfNumber(12,22,30); productOfNumber(1,12,31,4); return 0; } // Define the body of functions void productOfNumber(int p, int q) { cout<< endl << "The product is : "<< p*q; } void productOfNumber(int p, int q, int r) { cout<< endl << "The product is : "<< p*q*r; } void productOfNumber(int p, int q, int r, int s) { cout<< endl << "The product is : "<< p*q*r*s; }

Output:

The product is : 220 The product is : 7920 The product is : 1488

Operator Overloading

The ability to create operators with special meaning for data types is known as operator overloading. It is also referred to as ad-hoc polymorphism. The below example shows the working of operator overloading.

 

Example:

// Example of Operator overloading #include<iostream> using namespace std; class Count { int num; public: // Constructor Count(int N = 0) { this -> num = N; } // Overloading the -- operator. Count operator--() { Count c; c.num = --num; return c; } // Print value of num. void print() { cout << num << endl; } }; int main() { // creating object of Count class Count count1(98); cout << "Before using -- operator: "; count1.print(); // -- operator function is called Count count2 = --count1; cout << "After using -- operator: "; count2.print(); }

Output:

Before using -- operator: 98 After using -- operator: 97

Also Read – Operators in C++

Ways to Implement Run-Time Polymorphism in C++

In C++, we can implement run-time polymorphism in two ways.

 

Function Overriding

It is a special feature in C++ that allows the child class to provide its own implementation of the member function that is already defined in the parent class. The overridden functions need to have the same name, parameters, and return type.

 

Example:

// Example of function overriding #include<iostream> using namespace std; class Bird { public: void makeSound() { cout << "The bird makes a sound" << endl; } }; // Pigeon class inheriting Bird class class Pigeon : public Bird { public: // derived class overriding the makeSound() function of parent class void makeSound() { cout << "The pigeon coos" << endl; } }; int main() { // create object of Bird class and call its makeSound() function Bird *bird1 = new Bird(); bird1->makeSound(); // create object of Pigeon class and call its makeSound() function Pigeon *bird2 = new Pigeon(); bird2->makeSound(); return 0; }

Output:

The bird makes a sound The pigeon coos

Virtual Functions

Virtual functions are the member functions of the base class that can be overridden in a derived class. When we make a call to such functions using the reference of a base class, the virtual function is invoked. They are dynamic and called during runtime. A virtual function is declared in the base class using the “virtual” keyword.

 

Example:

// Example of Virtual function #include<iostream> using namespace std; // define a base class class Bird { public: // virtual function virtual void display() { cout << "This is Bird class virtual function." << "nn"; } void print() { cout << "This is bird class print method." << "nn"; } }; // define a child of Bird class class Pigeon : public Bird { public: // override function void display() { cout << "This is pigeon class display method." << "nn"; } void print() { cout << "This is pigeon class print method." << "nn"; } }; int main() { // create a reference of Bird class Bird* bird; Pigeon p; bird = &p; // this will invoke the virtual function bird->display(); // this will invoke the non-virtual function bird->print(); }

Output:

This is pigeon class display method. This is bird class print method.

Advantages of Polymorphism in C++

Below are some benefits of polymorphism:

 

  • It is efficient and saves memory space.
  • It increases the readability and consistency of the program.
  • It increases the execution speed of the program.
  • It enhances code reusability.
  • It offers flexibility in code and is easier to maintain.
  • It helps to reduce the coupling between different functionalities.

Disadvantages of Polymorphism in C++

Below are some drawbacks of polymorphism:

 

  • It makes code more complex when multiple inheritance hierarchies are involved.
  • It uses virtual functions that increase the binary size of the file.
  • It reduces the readability of the code.
  • Run-time polymorphism can result in performance issues for the codebase.

Comparison between Compile-time and Run-time Polymorphism

Here is the tabular comparison between the compile-time and run-time polymorphism:

 

Compile-time Polymorphism Run-time Polymorphism
It is widely known as static or early-binding polymorphism. It is widely known as dynamic or late-binding polymorphism.
It can be implemented through function and operator overloading. It can be implemented using virtual functions or function overriding.
In this method, function calls are resolved by the compiler. In this method, the function calls are not resolved by the compiler.
It offers less flexibility to the developers as everything is executed during compilation. It offers more flexibility as everything is executed during run-time.
It has a much faster execution rate. It has a comparatively slow execution rate.
Method overloading is an application of compile-time polymorphism. Method overriding is an application of run-time polymorphism.
It is less preferred for handling complex problems. It is better at handling complex problems.
It has no additional runtime overhead. It has an additional runtime overhead due to dynamic dispatch.

Conclusion

This concludes our discussion on polymorphism in C++. We discussed different ways to achieve polymorphism in detail, a real-life example, and their benefits and drawbacks. We saw different types of polymorphism with examples and, in the end, a tabular comparison between them to get a better understanding of the topic.

FAQs
Polymorphism is an object-oriented concept where an object can take on different forms and behaviour. It can be achieved through inheritance and virtual functions.
Inheritance allows a subclass to inherit properties from a base class. If we use a virtual function in the base class, then the child class can override those functions to implement its own behaviour, thereby achieving polymorphism.
In C++, a function in the base class that is marked “virtual” and can be overridden by the child class is known as a virtual function. It helps in achieving polymorphism.
In object-oriented programming, there are mainly two types of polymorphism: compile time, or static polymorphism, and run time, or dynamic polymorphism.
It increases the readability and consistency of the program, enhances code reusability, and escalates the execution speed of the program. Moreover, it makes code flexible and easier to maintain.

Updated on October 10, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved