Polymorphism example in C++

C++ProgrammingServer Side Programming

Polymorphism is a key feature of object oriented programming that means having multiple forms. This is divided into compile time polymorphism and runtime polymorphism in C++.

An example of compile time polymorphism is function overloading or operator overloading. An example of runtime polymorphism is function overriding.

An example of polymorphism using function overloading in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Example {
   public :
   void func(int a) {
      cout << "\nThe value of a: " << a;
   }
   void func(int a, int b) {
      cout << "\nThe value of a: " << a;
      cout << "\nThe value of b: " << b;
   }
   void func(char c) {
      cout << "\nThe value of c: " << c;
   }
};
int main() {
   Example obj;
   cout<< "\nOne int value";
   obj.func(5);
   cout<< "\nOne char value";
   obj.func('A');
   cout<< "\nTwo int values";
   obj.func(7, 2);
   return 0;
}

Output

The output of the above program is as follows.

One int value
The value of a: 5
One char value
The value of c: A
Two int values
The value of a: 7
The value of b: 2

Now, let us understand the above program.

The member function func() in class Example is overloaded. There are 3 func() functions with different parameters that can be selected as required. The code snippet for this is given as follows.

class Example {
   public :
   void func(int a) {
      cout << "\nThe value of a: " << a;
   }
   void func(int a, int b) {
      cout << "\nThe value of a: " << a;
      cout << "\nThe value of b: " << b;
   }
   void func(char c) {
      cout << "\nThe value of c: " << c;
   }
};

In the function main(), an object obj of class Example is created. The function func() is called with different arguments to demonstrate function overloading. The code snippet for this is given as follows.

int main() {
   Example obj;
   cout<< "\nOne int value";
   obj.func(5);
   cout<< "\nOne char value";
   obj.func('A');
   cout<< "\nTwo int values";
   obj.func(7, 2);
   return 0;
}
raja
Published on 21-Nov-2018 12:06:22
Advertisements