Will I really use it in my programming career? |
Yes.
I've read in a lot of places that it is not necessary as it usually causes ambiguity. |
Newbies tend to overuse/abuse operator overloading, so it's often downplayed to dissuade that. But really it's very useful.
So why do professors teach this and not something that is considered more useful? |
They teach it because it is useful and is a key part of the C++ language.
Can't I just accomplish everything that operator overloading accomplishes with a function like done above? |
Yes. Just about everything you can do with operator overloading you can do with a function. But that's not the point.
The point is... operator overloading is meant to make the code more intuitive.
Your Box class is a very bad example and that is a case where you should definitely
not use operator overloading. Conceptually, summing two boxes makes no logical sense... so overloading the + operator is a bad idea.
A good example is a mathematical vector class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Vector2
{
public:
float x, y;
// assume +, -, *, /, +=, -=, etc operators are overloaded
};
// then you can do things like this:
Vector2 a, b;
a.x = 5;
a.y = 3;
a *= 2.3f;
b = a;
a.x = 1;
a += b;
//etc
|
It effectively lets you create classes that function more like fundamental types. It allows code to be simpler and easier to follow. Compare that with the alternative:
1 2 3 4 5
|
a.multAssign(2.3f);
b = a;
a.x = 1;
a.addAssign(b);
|
Yes it accomplishes the same thing, but at-a-glance it isn't as intuitive.
Furthermore... it's useful for other kinds of types... like iterators...
1 2 3 4 5
|
// simple enough, but only because the ++ operator is overloaded for the iterator
for(someiterator i = vec.begin(); i != vec.end(); ++i)
// without overloading, you'd need to do something like this:
for(someiterator i = vec.begin(); i != vec.end(); i.next())
|
And the [] operator is frequently overloaded for container classes, like vector, map, string, etc.
And the << and >> operators are frequently overloaded in classes so that they can be easily sent to/from streams.
Operator overloading is all over the language and the standard library. So yes it is an important concept to learn.