0

I'm trying to understand member class initialization order but there is one thing that confusing me.

#include <iostream> 

class Foo {
        int y{7};
    public:
        Foo() 
        { 
            std::cout << "Foo Constructor"; 
        }

        explicit Foo(int yy) : y(yy) 
        { 
            std::cout << "Foo " << y << std::endl; 
        }

        int gety() 
        { 
            std::cout << "Foo::gety() returning "; 
            return y; 
        }
};

class Bar {
        int x;
    public:
        Bar() 
        { 
            std::cout << "Bar constructor" << std::endl; 
        }
        explicit Bar(int xx) : x(xx) 
        { 
            std::cout << "Bar "<< x << std::endl; 
        }

        int getx() 
        { 
            std::cout << "Bar::getx() returning "; 
            return x; 
        }
};

class Class {
    Bar bar;
    Foo foo;

    public:
        Class() : bar(foo.gety()), foo(5) 
        { 
            std::cout << "Class()\n";
        }
        void printxy() 
        { 
            std::cout << "Bar.x = " << bar.getx() << " \n" << "Foo.y = " <<  foo.gety() << std::endl; 
        }
};

int main(void)
{
    Class k;
    k.printxy();
    return 0;

}

I'm compiling this code with gcc --std=c++11 -Wuninitialized -Wall -pedantic

In Class object there is two members of class Foo and Bar. In initialization list I'm constructing firs bar object by using constructor that takes int as argument. But as i understand foo is not constructed yet because it's second in order on initialization list. So how i don't get any errors when using foo.gety() before it's constructed?

I think C++ is guarantee that any used object is constructed. So when Foo object is constructed? Or this is undefined behavior?

This is link for coliru example: Link

GoRo3
  • 161
  • 5

1 Answers1

2

Member variables are initialized in the order they are defined in the class. In your case bar will be initialized before foo (even if you change the order in the constructor initializer list).

What you're doing, using the uninitialized foo object, will lead to undefined behavior. There's no guarantee that a compiler will be able to catch it or even report it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621