0
0
C++programming~5 mins

Base and derived classes in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Base and derived classes
O(1)
Understanding Time Complexity

When using base and derived classes, it's important to know how the program's running time changes as the input grows.

We want to see how the number of operations changes when creating or using objects from these classes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Base {
public:
    void display() { /* simple print */ }
};

class Derived : public Base {
public:
    void show() { /* simple print */ }
};

int main() {
    Derived obj;
    obj.display();
    obj.show();
    return 0;
}
    

This code creates an object of a derived class and calls methods from both base and derived classes.

Identify Repeating Operations

Look for loops, recursion, or repeated calls.

  • Primary operation: There are no loops or recursion here; only simple method calls.
  • How many times: Each method is called once.
How Execution Grows With Input

Since there are no loops or repeated calls, the number of operations stays the same no matter how big the input is.

Input Size (n)Approx. Operations
103 (object creation + 2 method calls)
1003 (same as above)
10003 (still the same)

Pattern observation: The operations do not increase with input size; they stay constant.

Final Time Complexity

Time Complexity: O(1)

This means the program runs in constant time, doing the same amount of work regardless of input size.

Common Mistake

[X] Wrong: "Using derived classes always makes the program slower because of inheritance overhead."

[OK] Correct: Inheritance itself does not add repeated work or loops; method calls run once, so time stays constant.

Interview Connect

Understanding how base and derived classes affect time helps you explain your code clearly and shows you know how object-oriented design impacts performance.

Self-Check

What if the derived class had a loop inside one of its methods? How would the time complexity change?