2. Originally Posted by ugmusicbiz
when do you use overloading an operator? Any practical examples would be helpful.
It would be rather tedious to try and enumerate all reasonable uses of operator overloading (and there are many more possible abuses of operator overloading), but here are some examples:

One use of operator overloading that you might have encountered, or will encounter very soon, is to overload operator= to perform copy assignment (and in fact it is known as the copy assignment operator). For example, for some class X, you might want to be able to write:
Code:
```X a;
X b;
a = b;```
Later on when you have learnt about iterators and pointers, you will see that standard iterator syntax is inspired by pointer syntax (of which iterators are a generalisation). To make this syntax possible for iterators that are of class types, operator overloading is used.

Yet another example is when people write arbitrary precision mathematics libraries: they might use operator overloading to make the syntax more "natural", e.g., just as you can write (a + b) for int variables a and b, they might want to allow their users to write (x + y) for some "bignum" variables x and y.

Originally Posted by ugmusicbiz
It seems to me that overloading an operator is nothing more than taking what the operator does and putting it into a function that industrializes it.
I am not sure what you mean, but you can think of it in this way: an overloaded operator is a function with a special name that allows it to be called differently from normal functions (but you can call it like you would any other function).

3. This one takes me by surprise. Some people don't immediately understand what pointers are good for, but I didn't expect anyone not to understand the huge advantage of operator overloading.
Some random examples that would be so ugly without operator overloading:
Code:
```std::string a = "orange";
std::string b = "apple";
if (b < a)
std::cout << "told you so!" << std::endl;```
Code:
```complex j(1, 2);
complex k(-2, 1);
if (j*k == k/j)
std::cout << "didn't think so!" << std::endl;```
In fact if you make your own class to represent some kind of data and you don't provide the sensible set of operator overloads, then your class just sux. E.g. If you don't implement less-than then putting it in a std::set or sorting a vector of them etc just becomes unecessarily awkward.

Popular pages Recent additions