yandex
loader

please wait

  • Lucky Negi Mar-14-2019 06:25:45 AM ( 1 week ago )

     

    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 
    
    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
     

Please login

Similar Discussion

Recommended For You