What is operator overloading in classes?

Hello guys,

I've searched for this topic everywhere and tried reading my textbook, but I simply can't grasp this issue. I know that operator overloading is used to save time and space in programs, but what actually happens? If anyone can explain that to me in simple language, that'd be great!

Also, if you can tell me how the syntax for operator overloading works that'd be great!

But please, I'd really appreciate it if anyone would go to the trouble of being as simple as possible. :)

THANKS!
I think that if I will show an example it would be better any words. Let assume that there is class Point that denotes a point on surface. Each point has two coordinates x and y.

1
2
3
4
5
6
7
struct Point
{
   int x;
   int y;
   Point() : x( 0 ), y( 0 ) {}
   Point( int i, int j ) : x( i ), y( j ) {}
};

It would be good if we could add two Poinst. But in C++ there is 1) no such built-in type as Point; 2) the addition operator for our class is not defined.

That is it would be good to write

1
2
3
Point p1( 10, 10 );
Point p2( 5, 5 );
Point p3 = p1 + p2;


So as there is no such operator for our class in C++ we should define it ourselves.

1
2
3
4
const Point operator +( const Point &left, const Point &right )
{
   return ( Point( left.x + right.x, left.y + right.y ) );
}


So we have written operator function operator + for our class Point.

Now we can write either

Point p3 = operator +( p1, p2 );
or

Point p3 = p1 + p2;

The second statement is equivalent to the first statement but looks more clear. In the both cases operator function operator + is called.
Last edited on
Operator overloading just lets you define behavior for C++ operators so your class can be more "natural".

Common examples of this can be seen all over the standard lib classes like vector and string:

1
2
3
4
string foo = "first ";
foo += "second";  // appends "second" to the end of foo

cout << foo;  // prints "first second" 


Here, string's += operator is overloaded which allows you to use it this way. Without operator overloading, we would have to call a function like this:

 
foo.append( "second" ); // instead of foo += "second"; 


But note that the two are identical apart from how the code looks. Operator overloading just makes it more 'natural'. It doesn't improve performance or reduce code size or anything. Overloaded operators are exactly like member functions, only the syntax for calling them is different.
Operator overloading is used for main operators in c++ language overloading. So you can use them in natural way. Operators like +, -, *, / and so on.
My class for operator overloading.
http://cplusplus.shinigami.lt/2012/04/05/operator-overloading-in-class/

http://www.cplusplus.com/doc/tutorial%20%20/classes2/
Thanks a lot guys, specially vlad!
you explained it real nice.. I think i get it now.. :D
Topic archived. No new replies allowed.