Access specifier in Inheritance

The following text is from the link:

http://www.cplusplus.com/doc/tutorial/inheritance/

"Actually, most use cases of inheritance in C++ should use public inheritance. When other access levels are needed for base classes, they can usually be better represented as member variables instead."

Can anybody give a reason/logic behind the above statement along with a small test case maybe.

Regards
It's just common wisdom from object-oriented design, often stated as "prefer composition over inheritance". Inheritance has higher costs, in terms of maintenance, program semantics, etc. Here's the corresponding C++ Core Guideline:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c120-use-class-hierarchies-to-represent-concepts-with-inherent-hierarchical-structure-only "Do not use inheritance when simply having a data member will do"

For example, this is bad design:
1
2
3
class MyVector: private std::vector<int> {
  // ... other members
};

this is better:
1
2
3
4
class MyVector {
    std::vector<int> data;
// ... other members
};


Of course non-public inheritance is very common when using templates, when optimizing class layout, and in a few other situations that you aren't likely to encounter early on (as you're referencing a tutorial I assume you're a beginner), but if you're curious, they are listed at http://en.cppreference.com/w/cpp/language/derived_class#Protected_inheritance and http://en.cppreference.com/w/cpp/language/derived_class#Private_inheritance
Last edited on
thanks for your reply.
Topic archived. No new replies allowed.