Method overriding in C++ - Time & Space Complexity
When we use method overriding, we replace a method in a child class with a new version.
We want to see how this affects the time it takes to run the program.
Analyze the time complexity of the following code snippet.
class Base {
public:
virtual void display() {
// simple print
std::cout << "Base display" << std::endl;
}
};
class Derived : public Base {
public:
void display() override {
// overridden print
std::cout << "Derived display" << std::endl;
}
};
void callDisplay(Base* obj) {
obj->display();
}
This code shows a base class with a method and a derived class that overrides it. We call the method through a base pointer.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the display() method once per object.
- How many times: Each callDisplay call triggers exactly one method call.
Each call to display runs a simple print statement, which takes about the same time regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls, each simple print |
| 100 | 100 method calls, each simple print |
| 1000 | 1000 method calls, each simple print |
Pattern observation: The total work grows directly with the number of calls.
Time Complexity: O(n)
This means if you call the method n times, the total time grows in a straight line with n.
[X] Wrong: "Overriding a method makes the program slower because it adds extra work."
[OK] Correct: Overriding just changes which code runs, but each call still takes about the same time as before.
Understanding how method overriding affects time helps you explain object-oriented design choices clearly and confidently.
"What if the overridden method called another method with a loop inside? How would the time complexity change?"