简体   繁体   中英

When is a member object constructed when initialized in the constructor's initialization list?

If a member object data does not appear in the constructor's initialization list, then data is constructed by its default constructor.

If data appears in the constructor's initialization list, then it is simply initialized to the given value. Does this imply that there is no constructor call for creating data ? How is the new object data constructed then?

If data appears in the constructor's initialization list, then it is simply initialized to the given value.

No, it is initialised using whatever arguments are supplied. If it has a class type, then the arguments are passed to a suitable constructor.

Does this imply that there is no constructor call for creating data?

No. If it has a class type, then initialisation is done by calling a constructor.

When you're initializating data in the constructor's initialization list, its parametrized constructor is called.
Example:

#include <iostream>
#include <string>

class Data {
public:
    Data(int firstArg, std::string mSecondArg)
    {
        std::cout<<"parameterized constructor called"<<std::endl;
    }
};

class SomeClass {
public:
    SomeClass(int firstArg, std::string secondArg) : data(firstArg, secondArg) {}
private:
    Data data;
};

int main(int argc, char** argv) {
    SomeClass someObj = new SomeClass(0, new std::string("empty"));
    return 0;
}

With this code you will get output
parameterized constructor called

§12.6.2/7: The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of 8.5 for direct-initialization.

Which, in other words, means the normal constructor is called.

For example:

class Foo { Bar bar; Foo () : bar(...) { } };

is analoguous to creating Bar object as such:

Bar bar (...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM