FAQ 22.07 Are initializers executed in the same order in which they appear in the initialization list?

graphics/new_icon.gif

Not necessarily.

C++ constructs objects by initializing the subobjects of immediate base classes in the order the base classes appear in the class declaration, then initializing member objects in the order they appear in the class body layout. It uses this ordering so that it can guarantee that base class subobjects and member objects are destructed in the opposite order from which they are constructed. Member objects are destructed in the reverse order of the class body layout, then subobjects of immediate base classes are destructed in the reverse order they appear in the base class list in the class declaration. The order of the initialization list is irrelevant.

The following example demonstrates the fact that initialization order is tied to the order of the class layout rather than to the order of the initialization list. First, class Noisy prints a message during its constructor and destructor.

 #include <iostream> #include <string> using namespace std; class Noisy { public:   Noisy(const string& msg) throw();  ~Noisy() throw(); protected:   string msg_; }; Noisy::Noisy(const string& msg) throw() : msg_(msg) { cout << "construct " << msg_ << "\n"; } Noisy::~Noisy() throw() { cout << "destruct "  << msg_ << "\n"; } 

Now class Fred inherits from Noisy and also has two member objects of class Noisy.

 class Fred : public Noisy { public:   Fred() throw(); protected:   Noisy a_;   Noisy b_; }; 

The constructor of class Fred lists its three Noisy objects in a different order than the one in which they are actually initialized. The important thing to notice is that the compiler ignores the order in which members show up in the initialization list:

 Fred::Fred() throw() : b_("b_") , a_("a_") , Noisy("base") { } int main() { Fred x; } 

The constructor's initialization list order is (b_, a_, base-class), but the class body layout order is the opposite: (base-class, a_, b_). The output of this program demonstrates that the initialization list's order is ignored:

 construct base construct a_ construct b_ destruct b_ destruct a_ destruct base 

Even though the order of initializers in a constructor's initialization list is irrelevant, see the next FAQ for a recommendation.



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