Overloading Operators

Jul 9, 2012 at 8:13pm
I hear everyone talking about overloading operators, but I don't quite understand. How is that helpful? How can I use that?
Jul 9, 2012 at 8:15pm
For example consider a simple program

1
2
3
4
5
6
#include <iostream>

int main()
{
   std::cout << "Hello World\n";
}


Here overloaded operator << is used.:)

Another example

1
2
3
4
5
6
7
#include <complex>

int main()
{
   complex<double> c1( 10, 10 ), c2( 20, 20 );
   complex<double> c3 = c1 + c2;
}


Here overloaded operator + is used. :)
Last edited on Jul 9, 2012 at 8:20pm
Jul 9, 2012 at 8:40pm
Overloaded operator can be used if you want your operator to do another thing, for example, you can add 2 objects just like
1
2
3
4
5
6
obj objectA;
obj objectB;
obj objectC;

objectC = objectA + objectB;


But first you have to overload the "+" operator inside your obj class.
Jul 9, 2012 at 8:44pm
Oh okay. That makes sense. So, my user created classes; the compiler doesn't know how to add two user created classes, so I overload the operator+ to tell it exactly how?

That makes great sense. Thanks guys. :)
Jul 9, 2012 at 8:44pm
closed account (zb0S216C)
Overloading an operator informs the compiler how it should handle user-defined types with different operators. For example, let's pretend you were a compiler, and I gave you this expression: x_ + y_, where x_ and y_ are of type Type:

1
2
3
4
5
struct Type
{
    int i_;
    double d_; // I just realised what I wrote :)
};

How would you, the compiler, perform the addition? You wouldn't know, would you? By overloading the addition operator, I'm able to tell you how you should handle Type addition. For instance:

1
2
3
4
5
6
Type operator + (Type const &l_, Type const &r_)
{
    // OK, compiler, this is how you should handle it:
    // [Statement];
    // [Statement];
}

Now that you know how to handle Type addition, you follow my blueprints and be on your merry-way.

Wazzak
Jul 9, 2012 at 8:54pm
I'm gonna bookmark this thread. Haha. Thanks.
Topic archived. No new replies allowed.