On Sat, Feb 14, 2009 at 4:21 AM, 7stud – [email protected]
wrote:
Julian L. wrote:
I thought operator overloading was a non-oop way of specifying
multiple functions that each take different argument numbers?
That’s called function overloading. In C++, function overloading and
operator overloading are two different things.
That’s not the way I see it. In C++ operator overloading is
accomplished by
defining an overloaded function with special syntactic sugar to give it
the
same name as an existing operator:
e.g.
Class Complex {
Complex operator+(int);
Complex operator+(double);
Complex plus(int);
Complex plus(double);
…
};
This class declares that it has both overloaded versions of the binary +
operator as well as of the plus member function.
Operator overloading
requires a specific function signature for a given operator. Function
overloading on the other hand is used to create multiple function
signatures for a given function name.
As indicated above, they both do this.
Overloading means that the compiler distinguishes at compile time
between
calls to the same function or operator with the same name, based on the
type(s) of the arguments.
As this depends on having static types, overloading, either of functions
or
operators really isn’t a concept which is applicable to dynamically
typed
languages like Ruby. Use cases like mixed-mode arithmetic are handled
by
different techniques like the Numeric.coerce method in Ruby or double
dispatching in Smalltalk.
A side note on C++. Overloading is one of the mechanisms C++ provides
to
define polymorphism. Virtual functions are another, and probably better
known, Virtual functions can be overridden (which is different from
overloaded) by providing a new implementation in a subclass. Although
virtual functions can be overloaded, it’s not for the faint of heart:
http://answers.google.com/answers/threadview?id=379269
It’s a good example of why, when you scratch a little below the surface,
statically typed languages like C++ and dynamically typed language like
Ruby
are very different beasts and it’s dangerous to try to apply knowledge
of
one to the other without some deep thinking.
–
Rick DeNatale
Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale