Click here to Skip to main content
13,347,168 members (59,357 online)
Rate this:
Please Sign up or sign in to vote.
See more:
i usually get confused with operator overloading...plz reply with easy example
Posted 14-Apr-11 3:58am
Updated 14-Apr-11 3:59am
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

Refer below link


Rate this: bad
Please Sign up or sign in to vote.

Solution 5

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
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 {
  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;
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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:[^]

Rate this: bad
Please Sign up or sign in to vote.

Solution 4

Try this link:[^]
Nemanja Trifunovic 14-Apr-11 11:43am
SAKryukov 14-Apr-11 23:48pm
Compensated against the hate of people lacking sense of humor.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.180111.1 | Last Updated 14 Apr 2011
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100