What is the difference between public, protected and private inheritance in C++?
Hello colleagues! I started learning C++ and got to inheritance, but I'm confused about access modifiers when inheriting classes. Books explain it in a complicated way.\n\nLet's say there is a base class with different fields:\n\n```cpp\nclass Base {\npublic:\n int pub = 1;\nprotected:\n int prot = 2;\nprivate:\n int priv = 3;\n};\n```\n\nWhy in C++ do you need to write `class Derived : public Base` and not just `class Derived : Base`? What will change if I write `class Derived : private Base` or `class Derived : protected Base`?\n\nI tried different options but don't understand the logic. For example, if I inherit via `private`, can I access `pub` and `prot` inside the derived class? And from outside? What happens if I inherit a struct from a class? And most importantly — why are these three types of inheritance even needed?
No answers yet.
Log in to leave an answer