0
0
C++programming~5 mins

Encapsulation best practices in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Encapsulation best practices
O(n)
Understanding Time Complexity

Let's explore how the time cost grows when using encapsulation in C++ classes.

We want to see how accessing or modifying data inside a class affects performance as the program runs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Box {
private:
    int length;
public:
    void setLength(int l) { length = l; }
    int getLength() { return length; }
};

void updateBoxes(Box boxes[], int n) {
    for (int i = 0; i < n; i++) {
        boxes[i].setLength(i * 10);
    }
}
    

This code defines a class with private data and public methods to access it. Then it updates an array of these objects.

Identify Repeating Operations

Look for loops or repeated actions that take time.

  • Primary operation: The for-loop calling setLength on each object.
  • How many times: Exactly n times, once per object.
How Execution Grows With Input

As the number of boxes grows, the number of method calls grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to update all objects grows in a straight line with how many objects there are.

Common Mistake

[X] Wrong: "Using getter and setter methods makes the program slower in a way that changes the overall time complexity."

[OK] Correct: The methods add a tiny fixed cost per call, but the total time still grows linearly with the number of objects, so the big picture time complexity stays the same.

Interview Connect

Understanding how encapsulation affects performance helps you write clean code without surprises in speed as your program grows.

Self-Check

What if the setter method did some extra work like searching inside a list? How would the time complexity change?