Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of In Class Initialization versus Constructor Initialization List

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 ptris initialized before m1 and m2.

like image 810
ruhig brauner Avatar asked Mar 06 '23 11:03

ruhig brauner


1 Answers

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.

[class.base.init]#13.3

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

like image 94
songyuanyao Avatar answered Apr 27 '23 01:04

songyuanyao