Search code examples
c++initializer-list

Order of Initializer list in C++


I understand that for non-static members variables, order of evaluation in the initializer list is according to the order of declaration in the class.

Consider below example from isocpp

#include <iostream>

class Y {
   public:
      Y();
      void f();
};

Y::Y()      { std::cout << "Initializing Y\n"<<this<<"\n"; }

void Y::f() { std::cout << "Using Y\n"<<this<<"\n"; }

class X {
   public:
      X(Y& y);
};

X::X(Y& y) { y.f(); }

class Z {
   public:
      Z() throw();
   protected:
      X x_;
      Y y_;
};

Z::Z() throw() : y_(), x_(y_) {}

int main()
{
   Z z;
   return 0;
}

As X's ctor requires Y's reference we must ideally initialize y_ first; which means y_ has to be declared before x_.

I expected above program to give seg fault but below is my o/p. Can someone put some light on this.

-bash-4.1$ ./a.out
Using Y
0x7fffffffe0c1
Initializing Y
0x7fffffffe0c1

Solution

  • class Z {
       public:
          Z() throw();
       protected:
          X x_;
          Y y_;
    };
    
    Z::Z() throw() : y_(), x_(y_) {}
    

    In Z, you declare x_ before y_. Therefore, x is constructed before y_ regardless of the order of your initializers.

    And, initializing x_(y_) before y_ is constructed yields undefined behavior.


    I expected above program to give seg fault

    Undefined behavior is undefined. You should not expect anything in particular.