Topic 56 of 83
Polymorphism
Overview
Polymorphism means 'many forms'. It allows you to use a single interface to represent different types of actions or objects. It comes in two flavors: Compile-time (Static) and Run-time (Dynamic).
Syntax
cpp
// Polymorphism allows us to do things like this:
Animal* a = new Dog();
a->makeSound(); // Will call Dog's makeSound() if virtual, or Animal's if not.Common Pitfalls
- Confusing polymorphism with inheritance. Inheritance is the structure; Polymorphism is the behavior that utilizes that structure.
Interview Tips
- Polymorphism is the secret sauce for scalable design (like plugin architectures). It allows old code (base classes) to call new code (derived classes) without being modified.
Real-World Example
Conceptual overview.
example
cpp
/*
Imagine a function: void playMedia(Media* m) { m->play(); }
Because of polymorphism, you can pass Audio, Video, or Image objects
into that function, and it will 'play' them correctly without knowing
the exact type.
*/