• February 2nd, 2010, 05:33 PM
sidhu688
Hi guys,

Can someone tell me in very simple code that what exactly is operator overloading and what is it mainly used for...i read a couple of articles and all explained it using multidimensional arrays and vectors and i am beginner so really could'nt get it very clearly .

Thanks
Sid
• February 2nd, 2010, 06:14 PM
Mutant_Fruit
Operator overloading is so you can use the standard operators (+, -, *, /) with custom types.

Code:

```public struct ComplexNumber {     public double Real { get; set; }     public double Imaginary { get; set; }     public static ComplexNumber operator + (ComplexNumber left, ComplexNumber right)     {         return new ComplexNumber {             Real = left.Real + right.Real,             Imaginary = left.Imaginary + right.Imaginary         };     } } var a = new ComplexNumber (1, 2); var b = new ComplexNumber (3, 4); // 'c' is now the complex number (4, 6) var c = a + b;```
• February 3rd, 2010, 03:39 AM
cilu
Operators are defined for built in types, such as integers, floating point numbers or string. But you might also want to use operators like the arithmetic operators for your own classes. For instance the Complex class shown above, or maybe a Matrix class. You want to be able to sum or multiply to matrices. There isn't a + or * built in that is able to operate your matrices, because that's impossible. Or maybe you want to compare (<, > , !=, ==) Cars, Bounds, Clients, Stars, or whatever other types you define. So you can "overload" some operators. This means you can give them additional functionality to operate your defined classes. (operators are nothing but functions).
• February 3rd, 2010, 05:36 PM
rliq
Also if you do overload operators for your class, make sure their meaning is obvious. For example, if a, b and c are all Strings, then:

a = b + c; // concatenation is widely expected by coders

a = b - c; // not obvious what the designer of the String class meant
• February 4th, 2010, 01:32 AM
cilu
Yes, that is a good point. The common (natural) meaning of the operators should not be changed (should I say "overloaded"? ;) ).
• February 5th, 2010, 10:16 AM
sidhu688