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)
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 { ... }
source share