TITLE: idiom for order of initializing data members (Newsgroups: comp.lang.c++.moderated, 25 Jun 97) ESA: Pulkkinen Esa >class Z >{ > Y &yRef; > Z(); >public: > Z(Y &y); // does NOT assume ownership of the passed reference. > // ... >}; > >class X : public Z >{ > auto_ptr y; >public: > X(int param) : y(new Y(param)), Z(*y) {} // This is undefined behaviour. >}; > >This is undefined behaviour, because the base classes are initialized >(and so arguments to their constructors must be evaluated) before any >data members are. So y isn't initialized when the above passes it to Z. SUTTER: herbs@cntc.com (Herb Sutter) Right, so try using a private base class helper: class XImpl { protected: XImpl(int param) : y(new Y(param)) {} auto_ptr y; }; class X : private XImpl, public Z { public: X(int param) : XImpl(param), Z(*y) {} }; The XImpl subobject will be initialized before the Z subobject because nonvirtual base classes are initialized in the order they're written. No other code in X has to change, since X accesses the 'y' member as usual. This kind of thing has recently come up in our code, too. This solution doesn't affect the relationship between X and Z (it's still public inheritance and you don't need to modify the base class), and it doesn't affect clients of X and Z (they operate the same way as they would if your original code were allowed).