Thursday, July 18, 2013

C++ constructor member initializers run in member declaration order

TL;DR: Keep your C++ class member declaration order the same as your constructor member initializers order.

C++ guarantees that the member initializers in a constructor are called in order. However the order in which they are called is the order in which the associated members are declared in the class, not the order in which they appear in the member initializer list. For instance, take the following code. I would have thought it would print "three, one, two", but in fact it prints, "one, two, three".

   
      #include "stdafx.h"
#include <iostream>

class PrintSomething {
public:
 PrintSomething(const wchar_t *name) { std::wcout << name << std::endl; }
};

class NoteOrder {
public:
        // This order doesn't matter.
 NoteOrder() : three(L"three"), one(L"one"), two(L"two") { }

 PrintSomething one;
 PrintSomething two;
 PrintSomething three;
};

int wmain(const int argc, const wchar_t* argv[])
{
 NoteOrder note; // Prints one, two, three, not three, one, two!
 return 0;
}

No comments: