Consider this code sample:
class Base {
public:
Base( string& _object ) : object( _object ) {}
private:
string& object;
};
class Derived: public Base {
public:
Derived() : Base( object ) {}
private:
string object;
};
Obviously first Base
is constructed and it is passed a reference to a not yet constructed object.
Memory is allocated for the whole Derived
object, so Derived::object
is in legally accessible memory, just its constructor has not run. Base::Base()
doesn't call any methods of passed object, only stores the reference. It works in Visual C++ 9.
Is it safe according to C++ Standard?
It is safe, as long as you don't "use" the reference before object is constructed. You can use the base-from-member idiom to move object into a (private) base class which comes before Base, and thus be constructed before Base, if you need to change the construction order:
C++03 §3.8p6:
In a nutshell: don't access any members, methods, or pass it to anything that does. You can take its address and bind references to it.