Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of construction of member variables of a class undefined in c++? [duplicate]

Tags:

c++

Possible Duplicate:
Member fields, order of construction

If i have a class with two members like this:

class A
{
    int a;
    int b;
    A() {}
};

Is the order in which a and b are constructed undefined?

If I use cl, then no matter in which order I call the constructors, the members are always constructed in the order in which they are declared in the class. In this case it would always be a then b, even if I define the constructor for A like:

A() : b(), a() {}

But I am assuming that that is just the behaviour of the specific compiler.

like image 563
sji Avatar asked Sep 05 '12 16:09

sji


1 Answers

No. Members are constructed in the order in which they are declared.

You are advised to arrange your initializer list in the same order, but you are not required to do so. It's just very confusing if you don't and may lead to hard-to-detect errors.

Example:

struct Foo {
    int a; int b;
    Foo() : b(4), a(b) { }  // does not do what you think!
};

This construction is actually undefined behaviour, because you're reading an uninitialized variable in the initializer a(b).


Standard reference (C++11, 12.6.2/10):

— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

like image 151
Kerrek SB Avatar answered Oct 14 '22 11:10

Kerrek SB