Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
1.67/5 (5 votes)
See more:
i usually get confused with operator overloading...plz help...do reply with easy example
Posted
Updated 14-Apr-11 2:59am
v2

Refer below link

lilnk1[^]

link2[^]
 
Share this answer
 
The links posted above are all helpful in some regard. Something you should consider though, is that in C++ operator overloading is exactly the same as function overloading. Remember that the compiler will always try to implicitely convert code like
c = a + b;
into something like this
operator=(c,operator+(a,b));
As you can see, the second form uses standard function calls, and the names of these functions are operator= and operator+, respecticely.

For many built-in types, such as int or float, these operator functions have a default implementation. Also, the compiler will automatically define operator= for every struct or class that you define, unless you define it yourself (or prevent it by some compiler setting).

The main use of self-defined overloaded operators is for readability: if you have a class that represents objects which in a real world context could be combined with other objects using the symbols that are commonly used for operators, then it makes sense to define an operator function for your class that performs exactly this function.

For instance if you have 2D-Points P1 and P2 on your screen, you might want to express the vector from P1 to P2 like this: V = P1 - P2. If you define a class for a 2D-point however, the compiler will not understand this expression - you first have to define the operator- like this:
class Point2 {
public:
  int x;
  int y;
};
Point2 operator-(const Point2& p1, const Point2& p2) {
  Point2 v;
  v.x = p1.x-p2.x;
  v.y = p1.y-p2.y;
  return v;
}
 
Share this answer
 
This comes handy when you want to i.e. add some apples with pears or values that typically can't be operated by that operator i.e. time variables.

Anyway... Google is your friend: http://en.wikipedia.org/wiki/Operator_overloading[^]

HTH...
 
Share this answer
 
Try this link:

http://www.google.com[^]
 
Share this answer
 
Comments
Nemanja Trifunovic 14-Apr-11 11:43am    
+5.
Sergey Alexandrovich Kryukov 14-Apr-11 23:48pm    
Compensated against the hate of people lacking sense of humor.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900