1. Introduction to C++: A Comprehensive Guide with Code Examples - 2023 2. Mastering Data Types in C++: A Comprehensive Guide with Codes and Examples (2023) 3. Learn About Variables and Types of Variables in C++ | Codzify.com 4. Control Statements in C++: A Comprehensive Guide for 2023 5. C++ Tutorial: Understanding Switch Statements with Codes and Examples in 2023 6. Understanding Memory Allocation and Pointers in C++: A Beginners Guide 7. Functions in C++ 8. Call by value and Call by Reference in C++ in depth 9. Array in C++ 10. 2d arrays in C++ 11. Classes and Objects in C++ 12. Static Functions in C++ 13. Constructors and Destructors in C++ - A Complete Guide with Examples 14. Mastering Copy Constructor in C++ - Shallow vs Deep Copy with Examples | Codzify 15. Understanding Friend Functions in C++ Made Simple! 16. Inline Functions in C++ 17. this Pointer in C++ 18. Mastering Inheritance in C++: Types and Examples Explained 19. Types of Inheritance in C++ 20. Polymorphism in C++ Explained with Codes and Examples in 2023 21. Templates in C++ 22. Getting the Value of a MultiMap in C++: Step-by-Step Guide with Examples 23. Multimap Find and Replace Operator in C++: Step-by-Step Guide - Codzify Topics 24. Exploring the Next_Permutation Algorithm without STL in C++ - Codzify Topics 25. C++ - The Difference Between Map and HashMap in STL 26. Updating Values in a std::multimap in C++ - Codzify Topics 27. Which data structure sorts the elements on insertion in C++ STL? 28. Can we implement Red Black Tree in c++ by STL containers? 29. How to Dynamically Declare an Array of Objects with a Constructor in C++ - A Step-by-Step Guide 30. What is the difference between a pointer and an object in C++? 31. Mastering Red-Black Trees with STLs Internal Implementation: A Step-by-Step Guide

Polymorphism in C++ Explained with Codes and Examples in 2023

Article by: Manish Methani

Last Updated: October 16, 2021 at 8:04am IST
6 min 34 sec read

Polymorphism is a key concept in object-oriented programming, allowing objects of different classes to be treated as if they were objects of the same class. This enables code reusability and promotes modularity, making programs more flexible and easier to maintain. In this tutorial, we will explore the concept of polymorphism in C++ with examples and code snippets.

What is Polymorphism?

Polymorphism is a feature of object-oriented programming that allows objects of different types to be treated as if they were objects of the same type. This is achieved through the use of inheritance and virtual functions. When a base class pointer is used to point to an object of a derived class, the virtual functions of the derived class are invoked instead of those of the base class.

There are two types of polymorphism in C++:

  1. Compile-time polymorphism, also known as static polymorphism or method overloading, where a function or operator can be overloaded with multiple implementations that differ in the number or types of their parameters. The appropriate implementation is chosen based on the types of the arguments at compile time.

  2. Runtime polymorphism, also known as dynamic polymorphism or method overriding, where a virtual function defined in the base class is overridden by a function with the same name and signature in a derived class. The appropriate function to call is determined at runtime based on the actual type of the object being pointed to.

In Simple words, Poly = many , morphism = forms. 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.

Polymorphism in C++ with Examples

Let's take a look at some examples of polymorphism in C++.

Example 1: Compile-time Polymorphism

#include <iostream>
using namespace std;
class Shape {
  public:
     void area() {
      cout << "Base Class" << endl;
  }
};
class Circle : public Shape {
  public :
    void area() {
      out << "Area of Circle" << endl;
  }
};
class Rectangle : public Shape {
  public :
    void area() {
      out << "Area of rectangle" << endl;
  }
};

int main() {
  
Shape *p , *q;
p = new Circle();
p -> area();

q = new Rectangle();
q -> area();
  return 0;
}

Output:

Base Class
Base Class

Now what we did in this program is, Firstly we defined pointers of Shape Class. Then we created an object of Circle Class and assigned it to Shape Class pointers p. Now p is pointing to Circle class objects but Still method of base class is being called.

Similarly , We created an object of Rectangle Class and assigned it base class pointer q. Now q is pointing to area method of Rectangle class but still base class method is being printed.

Now think for a whle , if you are pointing to method
 of Circle class why base class method
 is being called ? 
Similarly,
If you are pointing to method of Rectangle 
Class why base class method is being called ?

So here comes Virtual Functions into existence.

Example 2: Runtime Polymorphism

If you want to call the method of a derived class to which your base class pointer is pointed, you have to name the member function of base class as virtual. Virtual functions are declared by using virtual keyword. The following program shows how to implement virtual functions

#include <iostream>
using namespace std;
class Shape {
  public:
     virtual  void area() {
      cout << "Base Class" << endl;
  }
};
class Circle : public Shape {
  public :
    void area() {
      out << "Area of Circle" << endl;
  }
};
class Rectangle : public Shape {
  public :
    void area() {
      out << "Area of rectangle" << endl;
  }
};
int main() {
  
Shape *p , *q;
p = new Circle();
p -> area();

q = new Rectangle();
q -> area();
  
return 0;
}

Output:

Area of Circle
Area of rectangle

We declared the Function of base class as virtual. So when base class pointer p is pointing to Circle Class method , method inside Circle class is being implemented rather than base class one. Similarly in case of Rectangle Class .

Pure Virtual Functions

If a base class virtual function doesn't have a function body then such a virtual function declares as pure virtual function.

class Shape
{
public :
    virtual void area() = 0;

};

The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function.

If a class contains pure virtual function then such class becomes an abstract class. We cannot create an object of an abstract class. But if required we can define pointer of its type.

Abstract class are defined to achieve polymorphism through late binding. Multiple classes can be derived from an abstract class. If a class is derived from an abstract class then it has to compulsorily override all the pure virtual functions declared in base class.

Learn Flutter, FlutterFlow,
Firebase & Angular.

Looking to learn how to create the production-ready apps
from scratch? Well, you are at the right place.

₹1299 or $15.56

Learn to create the Dating App using No-Code Tool FlutterFlow

Level: Advanced

Explore Curriculum
₹1299 or $15.56

Flutter Mobile App Development Course

Explore Curriculum
₹1299 or $15.56

The Complete Angular Course

Explore Curriculum
₹1299 or $15.56

Dart Programming for Absolute Beginners

Coming Soon
FREE

Next.js course

Start Watching
FREE

Fundamentals of Computer Programming Languages

Start Watching
FREE

Learn HTML, CSS & Bootstrap

Start Watching

Latest Web Stories

1

Learn how to open WhatsApp using FlutterFlow | Step by Step Guide

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App
Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer