polymorphism and function overriding

9/13/2025

polymorphism function overriding

Go Back

Polymorphism and Function Overriding in C++ Tutorial

Introduction

Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) that allows a single function, method, or operator to behave differently based on the context. In C++, polymorphism mainly comes in two types: compile-time (static) and run-time (dynamic).

Function overriding is a key technique used to achieve run-time polymorphism.


polymorphism  function overriding

Types of Polymorphism in C++

  • Compile-time Polymorphism

    • Achieved using function overloading and operator overloading

  • Run-time Polymorphism

    • Achieved using function overriding and virtual functions


Function Overriding (Run-time Polymorphism)

Function overriding allows a derived class to provide a specific implementation of a base class function. The base class function must be declared as virtual to enable run-time polymorphism.

Key Points:

  • Base function must be marked virtual

  • Derived function must have the same signature as base function

  • Decided at run-time using virtual table (vtable)

Example – Function Overriding

#include <iostream>
using namespace std;

class Developer {
public:
    virtual void work() {
        cout << "Developer is writing code." << endl;
    }
};

class TeamLead : public Developer {
public:
    void work() override {
        cout << "TeamLead is managing the development team." << endl;
    }
};

int main() {
    Developer* devPtr;
    Developer dev;
    TeamLead lead;

    devPtr = &dev;
    devPtr->work();  // Calls Developer's work()

    devPtr = &lead;
    devPtr->work();  // Calls TeamLead's overridden work()

    return 0;
}

Output:

Developer is writing code.
TeamLead is managing the development team.

Compile-time vs Run-time Polymorphism

FeatureCompile-timeRun-time
Achieved usingFunction overloading, operator overloadingFunction overriding (virtual)
Decision madeAt compile timeAt run time
PerformanceFasterSlightly slower
FlexibilityLessMore

Benefits of Polymorphism

  • Flexibility – Write generic code for multiple object types

  • Extensibility – Add new classes without changing existing logic

  • Code reuse – Reduce duplication by using base class references


Conclusion

Polymorphism enables objects to behave differently based on their type, enhancing flexibility and scalability of programs.

  • Compile-time polymorphism uses overloading.

  • Run-time polymorphism uses overriding with virtual functions.

Mastering polymorphism and function overriding will make your C++ code more modular and reusable.