Access control in inheritance in C++ - Time & Space 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.
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.
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.
Accessing members is a direct operation and does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 member accesses |
| 100 | 100 member accesses |
| 1000 | 1000 member accesses |
Pattern observation: Each member access takes the same time regardless of how many members or classes exist.
Time Complexity: O(1)
This means accessing a member through inheritance takes constant time, no matter how big the program is.
[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.
Understanding that access control does not slow down member access helps you focus on design, not performance worries.
"What if we added virtual inheritance or virtual functions? How would that affect the time complexity of member access?"