Function Overloading in C++
#include<iostream> using namespace std; class printData { public: void print(int i) { cout<<"printing int: "<<i<<endl; } void print(double f) { cout<<"Printing float: "<<f<<endl; } void print(char* c) { cout<<"Printing character:"<<c<<endl; } }; int main(void) { printData pd; //call print to print integer pd.print(5); //call print o print float pd.print(500.263); //call print to print character pd.print("Hello c++"); return 0; }
Operator Overloading in c++
we would have to pass two arguments for each operand as follows:
Box operator+(const Box&, const Box&);
example:
#include<iostream> using namespace std; class Box{ public: double getVolume(void) { return length*breadth*height; } void setLength(double len) { length=len; } void setBreadth(double bre) { breadth=bre; } void setHeight(double hei) { height=hei; } //overload + operator to add two Box objects. Box operator+(const Box& b) { Box box; box.length=this->length+b.length; box.breadth=this->breadth+b.breadth; box.height=this->height+b.height; return box; } private: double length; //Length of a box double breadth; //Breadth of a box double height; //Height of a box }; //Main function for the program int main() { Box Box1; Box Box2; Box Box3; double volume=0.0; //box1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); //box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); //Volume of box 1 volume=Box1.getVolume(); cout<<"Volume of Box1: "<<volume<<endl; //volume of box 2 volume=Box2.getVolume(); cout<<"Volume of Box2: "<<volume<<endl; //Add two object as follows: Box3=Box1+Box2; //volume of box3 volume = Box3.getVolume(); cout<<"Volume of Box3: "<<volume<<endl; return 0; }
Output:
Reference:
http://www.tutorialspoint.com/cplusplus/cpp_overloading.htm
There are some examples for various operators and list.You can go to reference link for this.Here I am pausing this as I am going to switvh to java as java is good for OOP. But I will be back to this C++ series if I get my free time again. đ
And If I get time I have a plan to start blogging about C++ vector, STL and Template library that is very helpful for contest programming.