Here we will see different types of polymorphism. Type is -
Ad-Hoc Multiple Morality is called overloading. This allows functions with the same name to act differently for different types. Both functions and operators can be overloaded. Some languages do not support operator overloading, but function overloading is common.
#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; }
Addition of numbers: 9 Addition of Strings: helloWorld
Inclusion of polymorphism is called subtyping. This allows the use of base class pointers and references to point to derived classes. This is runtime polymorphism. We don't know the actual object type before execution. We need virtual functions in C to achieve this inclusion polymorphism.
#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(); }
This is base class. This is derived class.
Forced polymorphism is called a cast. This type of polymorphism occurs when an object or primitive is converted to some other type. There are two types of casting. Implicit conversions are done using the compiler itself, explicit conversions are done using const_cast, dynamic_cast, etc.
#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); }
Value is: 100 Value is: 50
Parameter polymorphism is called early binding. This type of polymorphism allows using the same code for different types. We can get it by using templates.
#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; }
Max of (156, 78): 156 Max of (A, X): X
The above is the detailed content of Types of polymorphism - temporary, contained, parameterized and coercive. For more information, please follow other related articles on the PHP Chinese website!