Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common superclass.
We can treat objects of similar kinds in a uniform way.
There are 2 types of polymorphism in C++:
- Compile Time Polymorphism (achieved through Function Overloading)
- Runtime Polymorphism (achieved through Virtual Functions and Function Overriding)
What is the advantage of polymorphism?
Polymorphism provides flexibility and reusability in code. It allows objects of different types to be treated as objects of a common type, facilitating code maintenance and extensibility. More about these ideas in Object-Oriented Design
Thanks to polymorphism, we can do some really cool things with pointers (and that’s actually one of the main use cases of Pointers). See Static vs. Dynamic Type of Pointer
Example from https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm
Note: I have this shape example that I wrote myself in Constructor.
In the main loop,
You should be careful about this, see Virtual Function.
Some dangerous issues with Polymorphism
These are some super dangerous issues that arise due to polymorphism, and first introduced in CS247.
See Polymorphic Big Five.