// C++ program for function overloading #include<bits/stdc++.h>
usingnamespace std; classGeeks { public: // function with 1 int parameter voidfunc(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter voidfunc(double x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters voidfunc(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } };
intmain(){ Geeks obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return0;
//output : //value of x is 7 //value of x is 9.132 //value of x and y is 85, 64 }
/* Here, we declared a new res object. We then assigned the sum of the member variables of the current object (this) and the parameter object (obj) to the res object's var member variable. The res object is returned as the result. */
intmain(){ MyClass obj1(12), obj2(55); MyClass res = obj1+obj2;
voidshow() { cout<< "show base class" <<endl; } };
classderived:public base { public: voidprint()//print () is already virtual function in derived class, we could also declared as virtual void print () explicitly { cout<< "print derived class" <<endl; }
// Early binding because fun1() is non-virtual // in base p->fun_1();
// Late binding (RTP) p->fun_2(); //rewrited by derived class
// Late binding (RTP) p->fun_3(); //not rewrited by derived class
// Late binding (RTP) p->fun_4(); //Not the same function of fun_4(int x)
// Early binding but this function call is // illegal(produces error) because pointer // is of base type and function is of // derived class // p->fun_4(5);
//Look at here intmain() { Ninja n; Monster m; Enemy *e1 = &n; Enemy *e2 = &m;
e1->attack(); e2->attack();
return0; }
In this example, objects of different but related types are referred to using a unique type of pointer (Enemy*), and the proper member function is called every time, just because they are virtual.