0
0
C++programming~5 mins

Classes and objects in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Classes and objects
O(n)
Understanding Time Complexity

When working with classes and objects, it's important to know how the time to run your program changes as you create and use more objects.

We want to see how the program's speed changes when the number of objects grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Box {
public:
    int length;
    Box(int l) : length(l) {}
    int getLength() { return length; }
};

void printLengths(Box boxes[], int n) {
    for (int i = 0; i < n; i++) {
        std::cout << boxes[i].getLength() << std::endl;
    }
}
    

This code defines a simple class and prints the length of each Box object in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each Box object to call getLength()
  • How many times: Exactly once for each object in the array (n times)
How Execution Grows With Input

As the number of Box objects increases, the program does more work by calling getLength() for each one.

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

Pattern observation: The number of operations grows directly with the number of objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line as you add more objects.

Common Mistake

[X] Wrong: "Creating objects or calling methods inside a loop always takes constant time no matter how many objects there are."

[OK] Correct: Each object and method call adds work, so more objects mean more time spent.

Interview Connect

Understanding how loops over objects affect time helps you explain your code clearly and shows you know how programs scale.

Self-Check

"What if the getLength() method did a complex calculation instead of just returning a value? How would the time complexity change?"