0
0
C++programming~5 mins

Why encapsulation is required in C++ - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why encapsulation is required
O(n)
Understanding Time Complexity

We want to understand how using encapsulation affects the time it takes for a program to run.

Specifically, does hiding data and controlling access change how fast our code works?

Scenario Under Consideration

Analyze the time complexity of this simple class with encapsulation.


class Counter {
private:
    int count;
public:
    Counter() : count(0) {}
    void increment() { count++; }
    int getCount() { return count; }
};

void useCounter(int n) {
    Counter c;
    for (int i = 0; i < n; i++) {
        c.increment();
    }
    int result = c.getCount();
}
    

This code defines a class that hides its data and provides methods to change and read it.

Identify Repeating Operations

Look for loops or repeated actions that take time.

  • Primary operation: The loop calling increment() method.
  • How many times: Exactly n times, where n is input size.
How Execution Grows With Input

Each time we increase n, the loop runs more times, doing one increment each time.

Input Size (n)Approx. Operations
1010 increments
100100 increments
10001000 increments

Pattern observation: The work grows directly with n. Double n, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Encapsulation makes the program slower because of extra method calls."

[OK] Correct: The method calls are very fast and do not add extra loops or repeated work, so the overall time still grows linearly with input.

Interview Connect

Understanding how encapsulation affects performance helps you write clean code without worrying about slowing things down.

Self-Check

What if the increment() method did more work inside, like searching a list? How would the time complexity change?