DEV Community

Kyryl Rybkin
Kyryl Rybkin

Posted on • Updated on

The story about polymorphism

Do you want to magically put things in order in your head, and quickly?
Polymorphic variable == variable that can take values of different data types.
Polymorphic function == a function whose at least one argument is a polymorphic variable.

There are two types of polymorphic functions.

  1. Ad-hoc polymorphism - a function behaves differently for different types of arguments. For example, the function "draw()" - draws different geometric shapes in different ways for different objects.
  2. Parametric polymorphism - a function behaves the same for arguments of different types. An example is the "put an element in a container" function.

Polymorphism can be natural or artificial.

  1. Natural - when type information passes automatically, along with the value. And the language explicitly supports Ad-hoc polymorphism.
  2. Artificial polymorphism - when type information is dragged by separate parameters. For example, printf is a polymorphic function. Information about the type of arguments goes in the format string - the first argument.

Also, should distinguish static and dynamic polymorphism, when the type is resolved at compile time, or at run time.

Please pay attention - the word "class" and nothing related to OOP are not mentioned.

About OOP.

When you call a class method, it is a call to a function whose zero (implicit) argument is an object (this argument is referred to as this).

Consider natural polymorphism as an example.

Compile time:
Function overloading. The type of argument is part of the signature, that's why we have Ad hoc polymorphism.

Runtime:

  1. The pointer to the base class is a polymorphic variable. Any function that takes such an argument will have parametric polymorphism.
  2. A virtual function is ad-hoc polymorphic because of the presence of a single implicit argument. This is a weak property of the OO model in general, forcing scary patterns such as Visitor when ad-hoc polymorphism is required not on one argument, but on several. The solution to this problem is multi-methods, which are available in some object-oriented languages.

Seems to have missed nothing about polymorphism. So you can decompose any language yourself.

Top comments (0)