Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

§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 (...);

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top