0
0
C++programming~5 mins

Access control in inheritance in C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Access control in inheritance
O(1)
Understanding Time Complexity

When we use inheritance in C++, access control decides which parts of a base class are visible in a derived class.

We want to see how this visibility check affects the time it takes to access members as the program grows.

Scenario Under Consideration

Analyze the time complexity of accessing members with different inheritance access specifiers.


class Base {
public:
    int x;
protected:
    int y;
private:
    int z;
};

class Derived : public Base {
public:
    void access() {
        int a = x;    // public member
        int b = y;    // protected member
        // int c = z; // private member, not accessible
    }
};
    

This code shows how public, protected, and private members are accessed in inheritance.

Identify Repeating Operations

In this example, there are no loops or recursion, but member access happens repeatedly in larger programs.

  • Primary operation: Accessing class members through inheritance.
  • How many times: Each access is a single operation, but many accesses can happen as program size grows.
How Execution Grows With Input

Accessing members is a direct operation and does not grow with input size.

Input Size (n)Approx. Operations
1010 member accesses
100100 member accesses
10001000 member accesses

Pattern observation: Each member access takes the same time regardless of how many members or classes exist.

Final Time Complexity

Time Complexity: O(1)

This means accessing a member through inheritance takes constant time, no matter how big the program is.

Common Mistake

[X] Wrong: "Accessing protected or public members in inheritance takes longer as the class grows."

[OK] Correct: Member access is direct and does not depend on class size or inheritance depth for time cost.

Interview Connect

Understanding that access control does not slow down member access helps you focus on design, not performance worries.

Self-Check

"What if we added virtual inheritance or virtual functions? How would that affect the time complexity of member access?"