Re: "Polymorphism and Overloading in C++"
"A reader sent me an interesting question the other day. They asked if po=
lymorphism 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 betwee=
n "member functions" and "non-member functions" - that is, all functions ar=
e defined outside of the class and the "this" parameter is not implicit, bu=
t 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 unc=
omfortable)
Now, create some simple hierarchy (Shape, Circle, Triangle, etc.) and rewri=
te it as above and compare all function signatures - see how close is the r=
elation between polymorphism and overloading. If you think that the differe=
nce is in static vs. dynamic resolution (this would be convincing in C++ an=
d would explain the "virtual" nature of the function dispatch), then as the=
next step imagine that this is a scripting language where everything is dy=
namic anyway and is always based on the dynamic type of all actual paramete=
rs.
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 e=
xplained as: the ability of the code to work with data of different types.
--
Maciej Sobczak * http://www.inspirel.com