Why inheritance is used in C++ - Performance Analysis
We want to understand how using inheritance affects the time it takes for a program to run.
Specifically, how does calling functions through inheritance change the work done as the program grows?
Analyze the time complexity of this simple inheritance example.
class Animal {
public:
virtual void speak() { }
};
class Dog : public Animal {
public:
void speak() override { /* bark */ }
};
void makeSpeak(Animal* animals[], int n) {
for (int i = 0; i < n; ++i) {
animals[i]->speak();
}
}
This code calls the speak function on an array of Animal pointers, which may point to different derived types.
Look for repeated actions that take time.
- Primary operation: Loop through the array and call speak() on each object.
- How many times: Exactly once per element, so n times.
As the number of animals grows, the number of speak calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 speak calls |
| 100 | 100 speak calls |
| 1000 | 1000 speak calls |
Pattern observation: The work grows directly with the number of animals.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of objects increases.
[X] Wrong: "Inheritance makes the program slower in a way that grows faster than the number of objects."
[OK] Correct: Each call through inheritance still happens once per object, so the total work grows linearly, not faster.
Understanding how inheritance affects time helps you explain your design choices clearly and confidently.
"What if the speak function called another function inside a loop? How would that change the time complexity?"