The short definition
In computer science, polymorphism means that one name, such as a function, operator or type, can work with values of different types or behave in different ways depending on the situation. The word comes from Greek: poly means “many,” and morphe means “form.”
Where the idea shows up
Polymorphism appears in many programming languages, though the mechanics differ from one to the next:
- C++ uses virtual functions for behavior chosen while the program runs, and templates for code written once that works with many types.
- Java lets subclasses override methods, and it uses generics for type parameters.
- Python is dynamically typed. Code often works with any object that has the method it needs, a style often called duck typing.
- Rust uses traits, and generic functions can accept any type that implements a given trait.
The exact features differ, but the goal is the same: one piece of code, many possible types.
Polymorphic classes in C++
C++ uses the term in a more specific way for classes. A class is called polymorphic if it declares or inherits at least one virtual function.
class Logger { // not polymorphic: no virtual functions
public:
void log() const {}
};
class Writer { // polymorphic: has a virtual function
public:
virtual ~Writer() = default;
virtual void write() const {}
};
Overriding is the part that makes runtime polymorphism work, and it depends on the class having at least one virtual function. If that term is new, “What is function overriding with an example?” is a good next read.
Two broad groups
Computer scientists often split polymorphism into two groups:
- Ad hoc polymorphism gives a name separate definitions for particular types, such as overloaded functions.
- Universal polymorphism uses one definition that applies to all the types it fits, such as a template or a function that accepts any derived class.
“What is overloading and its types?” covers the first group in more detail.
Why the term matters when reading code
When you see “polymorphism” in documentation or a code review, it usually refers to one of three things: a base class with virtual functions, a template that works with many types, or a function overloaded for several types. Knowing which one is in use tells you when the choice is made, at compile time or at runtime, and what kinds of errors to expect.
Recap
- Polymorphism means one interface can work with many types or behaviors.
- In C++, runtime polymorphism uses virtual functions, and compile-time polymorphism uses templates and overloading.
- A polymorphic class in C++ is one with at least one virtual function.