Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Member fields, order of construction

In C++, when doing something like what you see below, is the order of construction guaranteed?

Logger::Logger()
    : kFilePath_("../logs/runtime.log"), logFile_(kFilePath_)
{
    // ...
}
like image 890
Paul Manta Avatar asked Jun 10 '11 15:06

Paul Manta


1 Answers

Yes, the order of construction is always guaranteed. It is not, however, guaranteed to be the same as the order in which the objects appear in the initializer list.

Member variables are constructed in the order in which they are declared in the body of the class. For example:

struct A { };
struct B { };

struct S {
    A a;
    B b;

    S() : b(), a() { }
};

a is constructed first, then b. The order in which member variables appear in the initializer list is irrelevant.

like image 180
James McNellis Avatar answered Sep 30 '22 09:09

James McNellis