1. Function Overloading : Compile time polymorphism: early binding: same function name with different types and number of arguments.
2. Virtual function: Run-time polymorphism: late binding: call function depending on where base pointer is pointing to.
Example:
// CPP program to illustrate
// Operator Overloading
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {
real = r;
imag = i;
}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main() {
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
// C++ program for function overriding
#include <bits/stdc++.h>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};Â
class derived:public base
{
public:
void print () //print () is already virtual function in derived class,
 //we could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};Â
//main function
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;
}
Comments
Leave a comment