More C++ Idioms/Base-from-Member
From Wikibooks, the open-content textbooks collection
Contents |
[edit]
Base-from-Member
[edit] Intent
To initialize a base class from a data-member of the derived class.
[edit] Also Known As
[edit] Motivation
Sometimes it becomes necessary to initialize a base class from a data member of the current/derived class. It sounds contradictory to the rules of C++ language because base classes are always initialized before any of the data members get a chance to execute their constructors, if any. The idiom boils down to pushing the parameter data member in a private base class and putting that private base class before the dependent base class in the derivation order. The language rules dictate that base classes are always initialized in the order of declaration.
[edit] Solution and Sample Code
Following code is obtained from Boost[1] library. Following code indicates the requirement.
#include <streambuf> // for std::streambuf #include <ostream> // for std::ostream class fdoutbuf : public std::streambuf { public: explicit fdoutbuf( int fd ); //... }; class fdostream : public std::ostream { protected: fdoutbuf buf; public: explicit fdostream( int fd ) : buf( fd ), std::ostream( &buf ) // This is not allowed. // buf can't be initialized before std::ostream. {} //... };
Here is the solution using base-from-member idiom.
#include <streambuf> // for std::streambuf #include <ostream> // for std::ostream class fdoutbuf : public std::streambuf { public: explicit fdoutbuf( int fd ); //... }; struct fdostream_pbase { fdoutbuf sbuffer; explicit fdostream_pbase( int fd ) : sbuffer( fd ) {} }; class fdostream : private fdostream_pbase , public std::ostream { typedef fdostream_pbase pbase_type; typedef std::ostream base_type; public: explicit fdostream( int fd ) : pbase_type( fd ), base_type( &sbuffer ) {} //... };
[edit] Known Uses
[edit] Related Idioms
[edit] References
- ↑ Boost Utility http://www.boost.org/libs/utility/base_from_member.html