Core Module
12 min forge
C++ Polymorphism
Understanding how objects of different types can be treated through the same interface.
C++ Polymorphism
π What is it
Polymorphism means "many forms". It occurs when we have many classes that are related to each other by inheritance. It allows functions to operate on objects of different types through pointers/references of the base class.
β‘ When to use
Essential for implementing complex systems where behavior varies by specific type (e.g., a Shape interface where Circle and Square implement draw()).
π§ Time complexity
- Virtual Call: $O(1)$ (plus a small overhead for vtable lookup).
π» Code example
cpp Standardclass Shape { public: virtual void draw() { std::cout << "Drawing shape" << endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing circle" << endl; } }; int main() { Shape *s = new Circle(); s->draw(); // Prints "Drawing circle" }
β Common mistakes
- Slicing: Passing derived objects by value to functions taking base types, losing all derived data.
- Forgetting the
virtualkeyword in the base class. - Not using
virtualdestructors. - Forgetting to use
overridekeyword (optional but helpful for catching errors).