Data hiding in C++ - Time & Space Complexity
We want to understand how the time it takes to run code changes when we use data hiding in C++ classes.
Specifically, does hiding data affect how long operations take as the program grows?
Analyze the time complexity of the following code snippet.
class Box {
private:
int length;
public:
void setLength(int len) { length = len; }
int getLength() { return length; }
};
int main() {
Box b;
b.setLength(10);
int len = b.getLength();
return 0;
}
This code defines a class with a private variable and public methods to set and get its value, demonstrating data hiding.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the setter and getter methods.
- How many times: Each method is called once in this example, no loops or recursion.
Since there are no loops or repeated calls, the time to run each of these methods stays the same no matter how many objects or calls you have.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls |
| 100 | 100 method calls |
| 1000 | 1000 method calls |
Pattern observation: The time grows directly with the number of method calls, one operation per call.
Time Complexity: O(n)
This means the time grows linearly with the number of times you call the methods accessing hidden data.
[X] Wrong: "Data hiding makes the program slower because accessing private data is complicated."
[OK] Correct: Accessing private data through simple methods is just as fast as accessing public data directly; the time depends on how many times you call the methods, not on data hiding itself.
Understanding how data hiding affects performance helps you explain design choices clearly and shows you know how code structure relates to efficiency.
"What if the getter method included a loop to process data before returning it? How would the time complexity change?"