Search code examples
c++ooppolymorphismlanguage-design

Polymorphism by function parameter


Ok - this may be a very stupid question, but it's been bothering me.

Is there a language where

class Animal;
class Ape : public Animal
{...}

void doStuff(Animal* animalPtr)
{
    cout << "doing animal stuff" << endl;
}

void doStuff(Ape* apePtr)
{
    cout << "doing ape stuff" << endl;
}

Animal *ape = new Ape();
doStuff(ape);

would yield "doing ape stuff"? (please bear with me using C++ syntax) To clarify, I want "a function that accepts an argument and acts on it according to the type of the argument".

And would it make sense? Of course, as a developer you'd need to take care since instances that look just like an Animal pointer might actually call Ape code, because at runtime it's an Ape instance being pointed to.


Solution

  • Yes, there are! This is called multiple dispatch. The Wikipedia article is very good. Sadly, it seem to only be supported via language extensions for most popular languages, but there are a few (mostly esoteric) languages which support it natively.