Polymorphsim
Polymorphsim: many forms
Two types of polymorphsim
- Compile Time Polymorphsim / Static Binding / Early Binding
- Function overloading
- Operator overloading
- Runtime Polymorphsim / Dynamic Binding / Lazy Binding
- Function overriding (using virtual functions)
Compile Time Polymorphsim
Function overloading
#include <iostream>
using namespace std;
class Test {
public:
void func(int x) {cout << "Integer" << endl; }
void func(double x) {cout << "Double" << endl; }
};
int main() {
Test t1;
t1.fun(10);
t1.fun(10.5);
return 0;
}
output
Integer
Double
Operator overloading
#include <iostream>
using namespace std;
class Complex {
public:
Complex() = default;
Complex(int r, int i) : real(r), imag(i) {}
Complex operator+(Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void show() { cout << real << "+" << imag << "i" << endl; }
private:
int real, imag;
};
int main() {
Complex c1(1, 3), c2(2, 5);
Complex c3 = c1 + c2;
c3.show();
return 0;
}
output
3+8i
Runtime Polymorphsim
When override
keyword is used, compiler checks if the member function in the derived class matches the signature of any virtual function in the base class.
#include <iostream>
using namespace std;
class Base {
public:
virtual void fun() { cout << "Base" << endl; }
};
class Derived : public Base {
public:
void fun() override { cout << "Derived" << endl; }
};
int main() {
Base *a = new Derived();
a->fun();
Derived b;
Base &c = b;
c.fun();
return 0;
}
output
Derived
Derived
From
Polymorphism In C++ | Static & Dynamic Binding | Lazy & Early Binding In C++ - YouTube