polymorphism and function overriding
polymorphism function overriding
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.
Compile-time Polymorphism
Achieved using function overloading and operator overloading
Run-time Polymorphism
Achieved using function overriding and virtual functions
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)
#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.
Feature | Compile-time | Run-time |
---|---|---|
Achieved using | Function overloading, operator overloading | Function overriding (virtual) |
Decision made | At compile time | At run time |
Performance | Faster | Slightly slower |
Flexibility | Less | More |
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
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.