๐Ÿงฑ C++ Object-Oriented Programming
Estimated reading: 3 minutes 44 views

๐ŸŒ€ 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++

TypeDescriptionKey Feature
Compile-timeFunction overloading or operator overloadingEarly binding
Run-timeBase pointer calling derived functionLate 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 s is a Shape*, it calls Circle::draw() due to runtime polymorphism.

๐Ÿงฌ Virtual Functions โ€“ The Backbone of Polymorphism

  • Declared using the virtual keyword
  • 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

FeatureCompile-Time (Static)Run-Time (Dynamic)
ExamplesFunction Overloading, TemplatesVirtual Functions, Method Overriding
Decision made atCompile timeRun time
PerformanceFasterSlightly slower
FlexibilityLimitedHigh
KeywordsNone (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 virtual and override wisely 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

C++ Polymorphism

Or Copy Link

CONTENTS
Scroll to Top