Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 331
mats Avatar asked Jan 30 '10 21:01

mats


People also ask

Can a parameter to a method be polymorphic?

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.

What do you mean by parametric polymorphism?

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.

What is function polymorphism?

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.

What is meant by function parameters?

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.


2 Answers

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.

like image 86
Steven Schlansker Avatar answered Oct 21 '22 13:10

Steven Schlansker


Take a look at the Visitor pattern

like image 25
mloskot Avatar answered Oct 21 '22 12:10

mloskot