Encapsulation best practices in C++ - Time & Space 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.
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.
Look for loops or repeated actions that take time.
- Primary operation: The for-loop calling
setLengthon each object. - How many times: Exactly
ntimes, once per object.
As the number of boxes grows, the number of method calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to setLength |
| 100 | 100 calls to setLength |
| 1000 | 1000 calls to setLength |
Pattern observation: The work grows directly with the number of objects.
Time Complexity: O(n)
This means the time to update all objects grows in a straight line with how many objects there are.
[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.
Understanding how encapsulation affects performance helps you write clean code without surprises in speed as your program grows.
What if the setter method did some extra work like searching inside a list? How would the time complexity change?