It is clear about public and private inheritance, but what about protected? Any example when we really need to use it and it gives us benefit?
Protected inheritance is something whose meaning eludes me to this day.
This is Scott Meyers opinion (Effective C++, 3rd Edition) on protected inheritance :).
However, this page is interesting: Effective C++: discouraging protected inheritance?.
The base-from-member idiom needs protected inheritance at times.
The problem that idiom addresses is the following: you sometimes need to initialize the base class with a member of the derived class, like 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 constructed after foo
, and thus the ostream
passed to foo::foo
is invalid.
You solve this with an auxiliary 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 constructed before foo
, and the ostream
passed to foo::foo
is valid.
If you want file
to become a protected member of bar
, you must use protected inheritance:
struct bar : protected bar_base, public foo { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With