0
0
C++programming~5 mins

Abstract classes in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract classes
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the number of shapes increases, the total time to draw all shapes grows directly with that number.

Input Size (n)Approx. Operations
1010 draw calls
100100 draw calls
10001000 draw calls

Pattern observation: The time grows in a straight line with the number of shapes.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw all shapes grows directly with how many shapes there are.

Common Mistake

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

Interview Connect

Understanding how abstract classes affect time helps you explain design choices clearly and shows you know how code structure relates to performance.

Self-Check

"What if we added nested loops inside the draw() method? How would the time complexity change?"