#include <iostream> class Base { public: int x = 10; protected: int y = 20; private: int z = 30; }; class Derived : public Base { public: void print() { std::cout << x << ' ' << y << '\n'; // std::cout << z << '\n'; // z is private in Base } }; int main() { Derived d; d.print(); std::cout << d.x << '\n'; // std::cout << d.y << '\n'; // y is protected return 0; }
In public inheritance, public members remain public and protected members remain protected in the derived class. The private members of the base class are not accessible in the derived class. So, x and y can be accessed inside Derived, but z cannot. Outside the class, only public members are accessible, so d.x works but d.y does not.
#include <iostream> class Base { public: int a = 5; protected: int b = 10; }; class Derived : protected Base { public: void show() { std::cout << a << ' ' << b << '\n'; } }; int main() { Derived d; d.show(); // std::cout << d.a << '\n'; // Is this allowed? return 0; }
With protected inheritance, the public and protected members of the base class become protected in the derived class. So inside Derived, both a and b are accessible. But outside, d.a is not accessible because it is now protected in Derived. Hence, the code inside show() runs fine, but accessing d.a in main() causes a compilation error.
#include <iostream> class Base { public: int val = 100; }; class Derived : private Base { public: void print() { std::cout << val << '\n'; } }; int main() { Derived d; d.print(); // std::cout << d.val << '\n'; // Is this allowed? return 0; }
With private inheritance, all public and protected members of the base class become private in the derived class. So inside Derived, val is accessible. But outside, d.val is not accessible because it is private in Derived. Therefore, print() works and prints 100, but accessing d.val in main() causes a compilation error.
public, protected, and private members, which inheritance type will make the base class public members inaccessible from outside the derived class?In private inheritance, all public and protected members of the base class become private in the derived class. This means they are not accessible from outside the derived class. Public and protected inheritance keep public members accessible outside the derived class. Virtual inheritance affects the way base classes are shared but does not change access levels.
#include <iostream> class Base { protected: int data = 42; }; class Derived : public Base { public: void show() { std::cout << data << '\n'; } }; int main() { Derived d; d.show(); std::cout << d.data << '\n'; return 0; }
The member data is protected in Base. This means it can be accessed inside Base and its derived classes, but not from outside. The call d.show() works because show() is a member of Derived which can access data. However, std::cout << d.data in main() tries to access data from outside, which is not allowed and causes a compilation error.