Reputation: 963
I want to initialize a bunch of members in-class to keep the source file cleaner. However, the objects take an argument I only receive via constructor and can initialize either in the constructor initialization list or in the constructor via assignment. (The second option would certainly not work.) This is basically the scenario:
In Header
class Foo
{
public:
Foo(Pointer * ptr);
private:
Pointer * ptr;
Member m1{ptr, "SomeText"};
Member m2{ptr, "SomeOtherText"};
}
In CPP
Foo::Foo(Pointer*ptr) :
ptr(ptr)
{
// ...
}
Now the question is: Does the standard say anything about the order of initialization between ptr
and m1
/ m2
? Obviously, this code would only work when ptr
is initialized before m1
and m2
.
Upvotes: 5
Views: 1478
Reputation: 172864
This is guaranteed by the standard that non-static data members will be initialized in the order of their declarations in the class definition. How they're initialized (via default member initializer or member initializer list) and the order of these initializers don't matter.
(13.3) - 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).
[ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. — end note ]
That means, the initialization order will always be ptr
-> m1
-> m2
.
Upvotes: 8
Reputation: 2306
The order in the class definition is important and dictates the order of initialization. There's no way to escape that order, other than redefining your class (i.e. swap the order around).
Once you're inside your constructor body, you can assign the value of any non-const member variable with any value you want, but that point, they have already been initialized. If you want to initialize a member before then, you have to do it before the constructor body -- i.e. use either Foo::Foo(Pointer * ptr) : ptr(ptr) {}
or by initializing them as you do with m1
and m2
.
Upvotes: 1
Reputation: 10315
It is standard-defined. The members are initialized in the order of declaration inside the class so Your code is perfectly valid. The potential danger is inconsistent initialization order in constructor with the member order - then still fields are initalized in declaration order.
Upvotes: 0