It must be initialized in the initialization list of each constructor. An example follows. class Fred { public: Fred(int& i) throw(); protected: int& i_; }; Fred::Fred(int& i) throw() : i_(i) <-- 1 { } int main() { int x; Fred a(x); //a.i_ will always be an alias for x }
Be sure to avoid binding a reference data member to an object passed to the constructor by value (for example, if parameter i were passed by value), since the reference (i_) would refer to a temporary variable allocated on the stack. This would create a dangling reference since value parameters disappear as soon as the function (the constructor in this case) returns. Depending on the phase of the moon, a dangling reference might crash the program. |