Overloaded operators are potentially excellent ways to do certain things, but are horribly easy to abuse.
Overloading the <<
and >>
operators makes it easy to extend C++'s streams, both in new kinds of streams, new objects for I/O, and both. Overloading ->
makes smart pointers almost a drop-in replacement for C++ pointers. Overloaded operators make it possible to have a string concatenation operator, and to build up new sorts of numbers that are syntactically just like int
s. Having them makes it possible to do things in libraries that would require language-level changes in other languages.
They do have their limitations. There is no operator suitable for exponentiation. There is only one multiplication operator, and in some cases there's more than one way to multiply (with 3D vectors, for example, there's at least the dot and cross products). The &&
, ||
, and comma operators cannot replicate their built-in functionality, since they can't have short-circuit evaluations and sequence points.
And, of course, they can be abused. There's no language requirement, for example, that arithmetic operators have to work anything like arithmetic. I've seen horrible things done in an effort to come up with a SQL notation that somebody thought was intuitive. In a C++ program that was badly written, it's impossible to know what, say, a = x * y;
does, since it's a.operator=(x.operator*(y));
, or maybe a.operator=(operator*(x, y));
or something, and the operator functions could be written to do anything.
Bjarne Stroustrup's intention in designing C++ was to include useful features regardless of the possibility of abuse, whereas James Gosling's intention in designing Java was to exclude excessively abusable features even if they were somewhat useful. It's not clear to me that either of those philosophies is correct or incorrect, but they are different.
Java was designed to avoid situations that would usually call for some C++ features, like operator overloading, multiple inheritance, and run-time type deduction, so they aren't often missed. Whether this is good or bad or neither is not something I know.
As far as teaching students, tell them not to overload operators themselves (except under defined conditions, such as functors and the assignment operator), but point out how the library uses overloaded operators. I wouldn't trust any C++ student to do them right, and if they're going to be able to do it they can and will learn it on their own. They will know it's tricky, because you forbade it in class. Some of the ones I would never trust with anything more complicated than a for
statement will find out how to overload operators, and will do anyway, but that's life.