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.

Simplified Coding for Beginners.








Download the Codzify
Mobile App


Mobile App Development, Web App Development, Programming Languages, Latest Tech News & lot more.

Codzify Mobile App

A self-paced learning Courses Created by an Engineer
For Engineers.

Premium

The Complete Angular Course

Instructor: Manish Methani

Explore Curriculum
Free

C Programming for Absolute Beginners

Instructor: Manish Methani

Start Watching
Premium

Flutter Mobile App Development Course

Instructor: Manish Methani

Explore Curriculum
Free

Learn HTML, CSS & Bootstrap

Instructor: Manish Methani

Start Watching

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
include_once 'codzify-footer.php'; ?>