Abstract classes in C++ - Time & Space Complexity
When using abstract classes, we want to know how the program's running time changes as we create and use objects from these classes.
We ask: How does the time to run methods from abstract classes grow with the number of objects?
Analyze the time complexity of the following code snippet.
class Shape {
public:
virtual void draw() = 0; // abstract method
};
class Circle : public Shape {
public:
void draw() override {
// drawing circle code
}
};
void drawShapes(std::vector<Shape *> &shapes) {
for (auto shape : shapes) {
shape->draw();
}
}
This code defines an abstract class Shape with a pure virtual method draw. It then draws all shapes in a list by calling draw on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the draw() method on each shape object.
- How many times: Once for each shape in the vector, so as many times as the number of shapes.
As the number of shapes increases, the total time to draw all shapes grows directly with that number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 draw calls |
| 100 | 100 draw calls |
| 1000 | 1000 draw calls |
Pattern observation: The time grows in a straight line with the number of shapes.
Time Complexity: O(n)
This means the time to draw all shapes grows directly with how many shapes there are.
[X] Wrong: "Using abstract classes makes the program slower because of extra overhead in method calls."
[OK] Correct: The main time cost comes from how many times methods run, not from the abstract class itself. Calling virtual methods has a small fixed cost, but the total time depends mostly on how many objects you process.
Understanding how abstract classes affect time helps you explain design choices clearly and shows you know how code structure relates to performance.
"What if we added nested loops inside the draw() method? How would the time complexity change?"