I understand polymorphism and vaguely understand overloading, but would appreciate someone that thoroughly understands there two concepts to explain what the categorical difference is and whether overloading is or is not a form of polymorphism (seems to be disagreement about this).
Polymorphism, at its core, is about multiple things which all have a certain set of consistent behavior, such that you can replace one with another within a particular algorithm or process. So long as they all provide the expected interface, the process still works.
Overloading doesn't really have such a foundation. It is merely the ability to name two or more functions with the same name, so long as they have different parameter lists. The compiler figure out which function you actually meant based on the types of the arguments you pass.
Now overloading can be used to create polymorphism. Consider the following:
template<typename T>
void func(T t) {call(t);}
This will call call
, passing t
as a parameter. This will work so long as you provide a type T
for which call(t)
is legitimate C++ code. You could do this by overloading the function call
for whatever types you are interested in using with func
:
void call(int);
void call(float);
void call(vector<int>);
In this way, func
is a function which is polymorphic (statically) with respect to its parameter. It can perform its operation on any type, so long as that type has the appropriate interface. That interface being the ability to call a function call
with a variable of that type.
func(5); //Legal
func(13.4); //Legal
func(vector<int>{4, 3, 2, 1}); //Legal
func(vector<float>{}); //NOT legal
Here, we use function overloading of call
to create a form of polymophism through the func
function. But this does not mean that overloading is polymorphism.
Overloading is a language tool. Polymorphism is a concept. Polymorphism is about making multiple objects all work the same way. Overloading is just a way to give different functions the same name.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments