๐ 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 :
