Base and derived classes in C++ - Time & Space 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.
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.
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.
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 |
|---|---|
| 10 | 3 (object creation + 2 method calls) |
| 100 | 3 (same as above) |
| 1000 | 3 (still the same) |
Pattern observation: The operations do not increase with input size; they stay constant.
Time Complexity: O(1)
This means the program runs in constant time, doing the same amount of work regardless of input size.
[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.
Understanding how base and derived classes affect time helps you explain your code clearly and shows you know how object-oriented design impacts performance.
What if the derived class had a loop inside one of its methods? How would the time complexity change?