0
0
C++programming~5 mins

Method overriding in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each call to display runs a simple print statement, which takes about the same time regardless of input size.

Input Size (n)Approx. Operations
1010 method calls, each simple print
100100 method calls, each simple print
10001000 method calls, each simple print

Pattern observation: The total work grows directly with the number of calls.

Final Time Complexity

Time Complexity: O(n)

This means if you call the method n times, the total time grows in a straight line with n.

Common Mistake

[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.

Interview Connect

Understanding how method overriding affects time helps you explain object-oriented design choices clearly and confidently.

Self-Check

"What if the overridden method called another method with a loop inside? How would the time complexity change?"