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.
Can a parameter to a method i.e. "catch(Animal a)" be polymorphic? A method can accept a polymorphic reference; this may give the method more flexibility than it would otherwise have.
Parametric polymorphism is a programming language technique that enables the generic definition of functions and types, without a great deal of concern for type-based errors. It allows language to be more expressive while writing generic code that applies to various types of data.
A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (e.g. a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.
Function parameters are the names listed in the function's definition. Function arguments are the real values passed to the function. Parameters are initialized to the values of the arguments supplied.
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.
Take a look at the Visitor pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With