1 of 26

POLYMORPHISM IN C++.

Rubi Kalita

2 of 26

���What is Polymorphism?

The word “polymorphism” means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

Types of Polymorphism:

  • Compile-time Polymorphism
  • Runtime Polymorphism

3 of 26

4 of 26

  1. Compile-Time Polymorphism

This type of polymorphism is achieved by function overloading or operator overloading.

  1. Function Overloading

When there are multiple functions with the same name but different parameters, then the functions are said to be overloaded, hence this is known as Function Overloading. Functions can be overloaded by changing the number of arguments or/and changing the type of arguments. In simple terms, it is a feature of object-oriented programming providing many functions that have the same name but distinct parameters when numerous tasks are listed under one function name. There are certain Rules of Function Overloading that should be followed while overloading a function.

5 of 26

B. Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can make use of the addition operator (+) for string class to concatenate two strings. We know that the task of this operator is to add two operands. So a single operator ‘+’, when placed between integer operands, adds them and when placed between string operands, concatenates them. 

6 of 26

7 of 26

8 of 26

9 of 26

10 of 26

11 of 26

12 of 26

13 of 26

14 of 26

15 of 26

16 of 26

17 of 26

18 of 26

19 of 26

20 of 26

21 of 26

2. Runtime Polymorphism

This type of polymorphism is achieved by Function Overriding. Late binding and dynamic polymorphism are other names for runtime polymorphism. The function call is resolved at runtime in runtime polymorphism. In contrast, with compile time polymorphism, the compiler determines which function call to bind to the object after deducing it at runtime.

22 of 26

A. Function Overriding�

Function Overriding occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden

23 of 26

#include <iostream>

using namespace std;

class base

{

public:

virtual void print()

{

cout << "print base class" << endl;

}

void show()

{

cout << "show base class" << endl;

}

};

24 of 26

class derived : public base

{

public:

void print()

{

cout << "print derived class" << endl;

}

void show()

{

cout << "show derived class" << endl;

}

};

25 of 26

int main()

{

base* bptr;

derived d;

bptr = &d;

// Virtual function, binded at // runtime (Runtime polymorphism)

bptr->print();

// Non-virtual function, binded // at compile time bptr->show();

return 0; }

26 of 26

Thank you.