When do we need protected inheritance?

This is clear about public and private inheritance, but what about the protected? Any example where we really need to use it, and it benefits us?

+6
source share
4 answers

The base-from-member idiom needs secure inheritance at times.

The problem is that the idiom addresses are as follows: sometimes you need to initialize a base class with a member of a derived class, for example, in

struct foo { virtual ~foo() {} protected: foo(std::ostream& os) { os << "Hello !\n"; } }; struct bar : foo { bar(const char* filename) : foo(file), file(filename) // Bad, file is used uninitialized {} private: std::fstream file; }; 

But file is built after foo , and so the ostream passed to foo::foo is not valid.

You solve this with a helper class and private inheritance:

 struct bar_base { std::fstream file; protected: bar_base(const char* filename) : file(filename) {} ~bar_base() {} }; struct bar : private bar_base, public foo { bar(const char* filename) : bar_base(filename), foo(file) {} }; 

Now bar_base is built before foo , and the ostream passed to foo::foo is valid.

If you want file become a protected member of bar , you must use protected inheritance:

 struct bar : protected bar_base, public foo { ... } 
+3
source

Protected inheritance is someone whose meaning eludes me to this day.

This is Scott Meyers' opinion (Effective C ++, 3rd Edition) about protected inheritance :).

However, this page is interesting: Effective C ++: discourages secure inheritance? .

+4
source

protected means that member variables will be accessible from subclasses, but not externally.

A very simple example might be a class that uses a variable (e.g. x ) to do internal calculations. If the subclass needs to do the same calculation, you probably need to access x . If you make it private, you cannot access this subclass by making it publicly available so that it is accessible to everyone. Protected is like a compromise.

+2
source

Protected is especially useful for abstract superclasses written with the knowledge of children. Protected members and methods are accessible to children and can preserve code replication without exposing them to the world outside the family of classes being implemented at that time.

0
source

Source: https://habr.com/ru/post/912144/


All Articles