🌀 C++ Polymorphism – Compile-Time & Run-Time Explained
🧲 Introduction – Why Polymorphism Matters in C++
Polymorphism is a powerful feature in object-oriented programming in C++ that enables a single function or interface to behave differently based on the object or context. It enhances flexibility, reusability, and maintainability in complex applications.
🎯 In this guide, you’ll learn:
- What polymorphism is and its types
- Compile-time vs run-time polymorphism
- Virtual functions, method overriding, and use cases
- Code examples with output and best practices
🔍 What Is Polymorphism?
The word “polymorphism” means “many forms.” In C++, it allows functions or methods to behave differently based on:
- Object type (Run-time Polymorphism)
- Arguments passed (Compile-time Polymorphism)
⚙️ Types of Polymorphism in C++
| Type | Description | Key Feature |
|---|---|---|
| Compile-time | Function overloading or operator overloading | Early binding |
| Run-time | Base pointer calling derived function | Late binding (virtual) |
💻 Code Examples – With Output
✅ Example 1: Compile-Time Polymorphism (Function Overloading)
#include <iostream>
using namespace std;
class Print {
public:
void show(int i) {
cout << "Integer: " << i << endl;
}
void show(string s) {
cout << "String: " << s << endl;
}
};
int main() {
Print p;
p.show(10);
p.show("Hello");
return 0;
}
🟢 Output:
Integer: 10
String: Hello
✅ Example 2: Run-Time Polymorphism (Virtual Function)
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};
int main() {
Shape* s;
Circle c;
s = &c;
s->draw(); // Calls Circle’s draw()
return 0;
}
🟢 Output:
Drawing Circle
🔍 Explanation:
draw()is a virtual function.- Even though
sis aShape*, it callsCircle::draw()due to runtime polymorphism.
🧬 Virtual Functions – The Backbone of Polymorphism
- Declared using the
virtualkeyword - Enables method overriding in derived classes
- Supports dynamic dispatch (late binding)
✅ Virtual Function Syntax:
class Base {
public:
virtual void display();
};
✅ Override in Derived Class:
class Derived : public Base {
public:
void display() override;
};
🧠 Polymorphism Comparison Table
| Feature | Compile-Time (Static) | Run-Time (Dynamic) |
|---|---|---|
| Examples | Function Overloading, Templates | Virtual Functions, Method Overriding |
| Decision made at | Compile time | Run time |
| Performance | Faster | Slightly slower |
| Flexibility | Limited | High |
| Keywords | None (implicit) | virtual, override |
💡 Best Practices & Tips
📘 Best Practice: Always use virtual in base classes when methods are meant to be overridden.
💡 Tip: Use override keyword in derived classes to prevent accidental mismatches.
⚠️ Pitfall: Forgetting virtual leads to object slicing—base method gets called instead of derived.
🛠️ Use Cases for Polymorphism
🔁 Game Engines: Entity → Player, Enemy, NPC, all override update()
🧾 Billing Systems: Invoice → GSTInvoice, DiscountedInvoice with override methods
🎨 Graphics Libraries: Shape → Circle, Rectangle, Triangle with draw() override
📦 Plugin Frameworks: Interface-based polymorphism to load modules dynamically
📌 Summary – Recap & Next Steps
🔍 Key Takeaways:
- Polymorphism allows flexible and extensible design
- C++ supports both compile-time (overloading) and run-time (virtual) polymorphism
- Use
virtualandoverridewisely for safe and correct inheritance behavior
⚙️ Real-World Relevance:
Used in rendering engines, data pipelines, simulations, frameworks, and plugin systems where behavior differs but interfaces remain unified.
✅ Next Steps:
- Learn about Abstraction and Encapsulation
- Explore Virtual Destructors and VTables
❓FAQ – C++ Polymorphism
❓Is polymorphism only used with inheritance?
✅ For run-time polymorphism, yes—it relies on virtual functions in inheritance.
❓Is function overloading the same as polymorphism?
✅ Yes, function overloading is compile-time (static) polymorphism.
❓Can constructors be virtual?
❌ No. Constructors cannot be virtual, but destructors should be if the class is used polymorphically.
❓What is object slicing?
⚠️ It occurs when a derived object is assigned to a base object—not a pointer or reference—causing loss of derived-specific data.
❓What happens if I forget virtual in the base class?
⛔ The base version of the function is called, even when using a derived class object—breaking polymorphism.
Share Now :
