Operator overloading feature of c++ assigns a new meaning to the existing operators, but original meaning cannot be changed.
Unary operator overloading
int a, b, c;
void getdata(int x, int y, int z)
a=x; b=y; c=z;
a=-a; b=-b; c=-c;
cout<<"\n t="; t.show();
-t; //t- not allowed
cout<<"\n t"; t.show();
Overloading Binary Operator
float x, y;
complex(float a, float b)
complex complex::operator+(complex c)
complex c1, c2, c3;
cout<<"\n c1="; c1.display();
Rules for overloading operators
1. Only existing operators can be overloaded.
2. The overloaded operator must have at least one operand.
3. We cannot change the basic meaning of an operator.
4. Overloaded operator follow the syntax rule of the original operator.
5. These operators cannot be overloaded:
Sizeof- size of operator
• - membership "
•*- pointer to member "
::- scope resolution "
?:- conditional operator
6. A friend function cannot overload the following :
= - Assignment operator
() - function call"
- subscribing "
-> - class member access "
member function can overload them.
7. Binary operators, overloaded through member function takes one expliar argument whereas in case of friend function. It takes two explicit arguments.
8. Unary operators, overloaded through member function takes zero explicit argument whereas in case of friend function it takes one explicit argument.