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 Standard
class 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 virtual keyword in the base class.
  • Not using virtual destructors.
  • Forgetting to use override keyword (optional but helpful for catching errors).