Operator Overloading in C++
What is Operator Overloading in C++?
Explanation
Operator Overloading is a method to define additional task or special meaning to an operator in refernce to an class. Operators that cannot be overloaded are class member access operator
(.,.*), scope resolution operator
"::",
"sizeof" operator and conditional operator
"?:".
Example :
#include <iostream.h> using namespace std; class space { int x, y, z; public: void getdata(int a, int b, int c); void display(void); void operator-(); }; void space :: getdata(int a, int b, int c) { x=a; y=b; z=c; } void space :: display(void) { cout << x << ""; cout << y << " "; cout << z << " "; } void space :: operator-() { x=-x; y=-y; z=-z; } int main() { space S; S.getdata(10, -20, 30); cout << "Values before overloading:: " << "\n"; S.display(); cout << "\n"; -S; cout << "Values after overloading:: " << "\n"; S.display(); return 0; } |
Result :
Values before overloading::
10-20 30
Values after overloading::
-10 20-30
In the above example the unary "-" operator is used to overload the objects got using "getdata()" of the class space. Usually the unary "-" operator is changes the sign, but here it is done for the objects of an class "space".
This is operator overloading in C++.