×

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example of polymorphism is when two people have distinct qualities at the same time. At the same time, he is a parent, a spouse, and a worker. As a result, the same individual behaves differently in different settings. Polymorphism is the term for this. One of the most significant characteristics of Object Oriented Programming is polymorphism.

Polymorphism in C++ is primarily classified into two types:

  • Polymorphism in compile time
  • Polymorphism at Runtime
C++ Polymorphism

Polymorphism at compile time

 This sort of polymorphism is done by function or operator overloading.

  • Function Overloading: When there are numerous functions with the same name but distinct arguments, this is referred to as overloading. Changes in the amount of arguments or the kind of arguments can cause functions to become overloaded.
  • Overloading Operators:  C++ also allows you to overload operators. For example, we can use the string class's operator ('+') to concatenate two strings. This is the addition operator, and its job is to add two operands. So, when the operator '+' is used between integer and string operands, it adds them together, and when it is used between string operands, it concatenates them.

Polymorphism at Runtime

Function Overriding is used to create this form of polymorphism.

  • Function overriding, on the other hand, happens when a derived class defines one of the base class's member functions. It's alleged that the basic function has been overridden.
  • Virtual function: The term virtual is used to declare a virtual function. A virtual function's return type can be int, float, or void. A virtual function is a base class member function. In a derived class, we can redefine it. It's a type of polymorphism known as run-time polymorphism. The virtual function must be declared in the base class using the term virtual. A virtual function isn't the same as a static function. The virtual function is used to instruct the compiler whether the function should be dynamically bound or late bound. If it's required to refer to all of the distinct classes' objects using a single pointer. This is due to the fact that we will need to build a reference to the base class that will refer to all of the derived objects.
  • Pure Virtual Function: We call such functions "Do-nothing functions" or "Pure virtual functions" when they have no definition. This function's declaration occurs without a definition in the base class.
C++ Polymorphism
Polymorphism at compile timePolymorphism at Runtime
At compilation time, the function to be called is known.At runtime, the function to be called is known.
Overloading, early binding, and static binding are other terms for the same thing.Overriding, Dynamic binding, and late binding are other terms for it.
Overloading is a compile-time polymorphism in which many methods with the same name but different numbers or types of arguments are created.Overriding is a sort of run-time polymorphism in which more than one method has the same name, number of parameters, and parameter type.
Function overloading and operator overloading are used to achieve this.Virtual functions and pointers are used to accomplish this.
As it is known at build time, it allows quick execution.It delivers delayed execution due to the fact that it is known at run time.
It is less flexible since almost everything happens at build time.It's more adaptable since everything happens at the same time.

In C++, a real-time example of polymorphism

When we connect a concept to a real-life example, it becomes evident.

Let's look at a few real-world polymorphism instances in C++.

  • At the same time, a person might have many positions and responsibilities. A woman has several hats to wear throughout her life, including mother, wife, daughter, daughter-in-law, sister, and so on.
  • A guy acts as an office worker, a son or spouse at home, a mall consumer, and so on.
  • A mobile phone is a single device with several functions such as a camera, radio, and so on.

Example of a run-time polymorphism with data members

#include <iostream>    
using namespace std;    
class Animal {                                           
class declaration.  
    public:    
    string color = "White";      
};     
class Rabbit: public Animal                      
Animal class.  
{      
 public:    
    string color = "pink";      
};    
int main(void) {    
     Animal r= Rabbit();      
    cout<<r.color;     
}    

Output

White

Example of run-time polymorphism with two derived classes

#include <iostream>
using namespace std;


class Polygon {
    public:
    virtual void show() {
        cout<<"It is a polygon"<<endl;
    }
};
class Hexagon : public Polygon {
    public:
    void show() {
        cout<<"Hexagon is a 6 sided polygon"<<endl;
    }
};
class Pentagon : public Polygon {
    public:
    void show() {
        cout<<"Pentagon is a 5 sided polygon"<<endl;
    }
};


int main() {
  Polygon *P;
  Hexagon h;
  Pentagon p;
  P = &h;
  P->show();
  P = &p;
  P->show();
  return 0;
}

Output

Hexagon is a 6 sided polygon
Pentagon is a 5 sided polygon

Related Topics

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

C++ Switch

In C++, an expression or variable can be tested against a range of constant values using a switch statement, which is a control flow statement. It offers a productive method...

4 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.