Types of Polymorphisms - Ad-hoc, Inclusion, Parametric & Coercion

CServer Side ProgrammingProgramming

Here we will see different types of polymorphism. The types are −

  • Ad-Hoc
  • Inclusion
  • Parametric
  • Coercion

The Ad-Hoc polymorphism is called as overloading. This allows function with same name to act in different manner for different types. The function and the operator both can be overloaded. Some language does not support operator overloading, but function overloading is common.

Example

#include<iostream>
using namespace std;
int add(int a, int b) {
   return a + b;
}
string add(string a, string b) {
   return a + b; //concatenate
}
int main() {
   cout << "Addition of numbers: " << add(2, 7) << endl;
   cout << "Addition of Strings: " << add("hello", "World") << endl;
}

Output

Addition of numbers: 9
Addition of Strings: helloWorld

The Inclusion polymorphism is called as subtyping. This allows to point derived classes using base class pointers and references. This is runtime polymorphism. We do not know type of the actual object until it is executing. We need virtual function in C++ to achieve this inclusion polymorphism.

Example

#include<iostream>
using namespace std;
class Base {
   public:
      virtual void print() {
         cout << "This is base class." << endl;
      }
};
class Derived : public Base {
   public:
      void print() {
         cout << "This is derived class." << endl;
      }
};
int main() {
   Base *ob1;
   Base base_obj;
   Derived derived_obj;
   ob1 = &base_obj; //object of base class
   ob1->print();
   ob1 = &derived_obj; //same pointer to point derived object
   ob1->print();
}

Output

This is base class.
This is derived class.

The Coercion polymorphism is called as casting. This type of polymorphism occurs when an object or the primitive is cast into some other type. There are two type of casting. The implicit casting is done using compiler itself, and explicit cast is done using const_cast, dynamic_cast etc.

Example

#include<iostream>
using namespace std;
class Integer {
   int val;
   public:
      Integer(int x) : val(x) {
   }
   operator int() const {
      return val;
   }
};
void display(int x) {
   cout << "Value is: " << x << endl;
}
int main() {
   Integer x = 50;
   display(100);
   display(x);
}

Output

Value is: 100
Value is: 50

The Parametric polymorphism is called as Early Binding. This type of polymorphism allows to use same piece of code for different types. We can get it by using templates.

Example

#include<iostream>
using namespace std;
template <class T>
T maximum(T a, T b) {
   if(a > b) {
      return a;
   } else {
      return b;
   }
}
int main() {
   cout << "Max of (156, 78): " << maximum(156, 78) << endl;
   cout << "Max of (A, X): " << maximum('A', 'X') << endl;
}

Output

Max of (156, 78): 156
Max of (A, X): X
raja
Published on 20-Aug-2019 10:31:05
Advertisements