> "A reader sent me an interesting question the other day. They asked if polymorphism and overloading were essentially the same thing."
>
> "My initial reaction was Huh?"
They are very closely related and in some contexts might be equivalent.
For the sake of mental exercise imagine that there is no distinction between "member functions" and "non-member functions" - that is, all functions are defined outside of the class and the "this" parameter is not implicit, but explicit. So, instead of this:
class MyClass
{
public:
void foo(int i) { /* ... */ }
private:
/* data fields */
};
you would have this:
class MyClass { /* data fields */ };
void foo(MyClass & this, int i)
{
// ...
}
(you can replace "this" with "self" or some other name, if "this" seems uncomfortable)
Now, create some simple hierarchy (Shape, Circle, Triangle, etc.) and rewrite it as above and compare all function signatures - see how close is the relation between polymorphism and overloading. If you think that the difference is in static vs. dynamic resolution (this would be convincing in C++ and would explain the "virtual" nature of the function dispatch), then as the next step imagine that this is a scripting language where everything is dynamic anyway and is always based on the dynamic type of all actual parameters.
Now, where's the difference? ;-)
Note that in some literature templates are also considered to be a kind of polymorphism, which then becomes a very broad concept that can be shortly explained as: the ability of the code to work with data of different types.
--
Maciej Sobczak *
http://www.inspirel.com