Concept Flow - Access control in inheritance
Base class members
Inheritance type?
Derived class access
Shows how base class members' access changes in derived class depending on inheritance type.
class Base { public: int x; protected: int y; private: int z; }; class Derived : public Base { void func() { x = 1; y = 2; // z not accessible } };
| Step | Code Line | Member Access | Access Allowed? | Reason |
|---|---|---|---|---|
| 1 | class Base { public: int x; } | x | Public | Accessible everywhere |
| 2 | class Base { protected: int y; } | y | Protected | Accessible in Base and derived classes |
| 3 | class Base { private: int z; } | z | Private | Accessible only in Base |
| 4 | class Derived : public Base | Inheritance type | Public | Public inheritance keeps access levels |
| 5 | Derived::func() { x = 1; } | x | Accessible | x is public in Base and remains public |
| 6 | Derived::func() { y = 2; } | y | Accessible | y is protected in Base and remains protected |
| 7 | Derived::func() { z = 3; } | z | Not accessible | z is private in Base, not inherited |
| 8 | class Derived : protected Base | Inheritance type | Protected | Public and protected become protected |
| 9 | Derived::func() { x = 1; } | x | Accessible | x becomes protected in Derived |
| 10 | Derived::func() { y = 2; } | y | Accessible | y remains protected |
| 11 | Derived::func() { z = 3; } | z | Not accessible | z is private in Base, not inherited |
| 12 | class Derived : private Base | Inheritance type | Private | Public and protected become private |
| 13 | Derived::func() { x = 1; } | x | Accessible | x becomes private in Derived |
| 14 | Derived::func() { y = 2; } | y | Accessible | y becomes private in Derived |
| 15 | Derived::func() { z = 3; } | z | Not accessible | z is private in Base, not inherited |
| 16 | Outside Derived: obj.x | x | Depends on inheritance | Public inheritance: accessible; protected/private: not accessible |
| 17 | Outside Derived: obj.y | y | Not accessible | Protected and private members not accessible outside |
| 18 | Outside Derived: obj.z | z | Not accessible | Private member never accessible outside Base |
| 19 | End of example | - | - | Demonstrates access control changes in inheritance |
| Member | Base Access | Public Inheritance | Protected Inheritance | Private Inheritance |
|---|---|---|---|---|
| x | public | public | protected | private |
| y | protected | protected | protected | private |
| z | private | not inherited | not inherited | not inherited |
Access control in inheritance: - Base class members: public, protected, private - Public inheritance: public->public, protected->protected - Protected inheritance: public->protected, protected->protected - Private inheritance: public->private, protected->private - Private members never inherited - Outside access depends on final access level