C++ polymorphism
Polymorphism means one interface, many implementations.
In C++, this usually means calling a function through a base class pointer or reference, while the real object decides which function runs.
Example idea:
The caller only knows that it has an Animal.
The actual behavior depends on whether the object is a Dog, Cat, or another
derived class.
Simple example
Use virtual in the base class and override in the derived class.
Output:
make_sound() receives an Animal&, but it still calls the correct speak()
function for the real object.
That is runtime polymorphism.
Why virtual matters
Without virtual, C++ chooses the function based on the reference or pointer
type.
With virtual, C++ chooses the function based on the real object type.
Use override in derived classes so the compiler checks that you really are
overriding a virtual function.
Key point
Polymorphism lets you write code that works with a general type, like Animal,
while still getting specialized behavior from derived types, like Dog and
Cat.
-
Without
virtual, C++ uses the pointer/reference type. -
With
virtual, C++ uses the real object type.
A polymorphic class in C++ is a class that has at least one virtual function.
polymorphic class
Yes: for a class to be polymorphic, a virtual function must exist in the class itself or be inherited from a base class.
Example:
Animal is polymorphic because it has a virtual function.