FAQ 22.06 How is a reference data member initialized?

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 } 

(1) References must be initialized in the initialization list

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net