mercredi 28 septembre 2016

Using braced initialization for child struct [duplicate]

This question already has an answer here:

If I have a struct, I can initialize an instance of it without having to manually create a constructor, like this:

struct Struct {
    int x;
    int y;
};

int main() {
    Struct data{1, 2};
    //Struct data = {1, 2};  //Also works
}

However, I can no longer do this if the struct inherits from something else:

struct Parent {
    int x;
};

struct Child : public Parent {
    int y;
};

int main() {
    Child data{1, 2};
    //Child data = {1, 2};  //Also fails, with same error
}

The compiler (GCC 5.3.0) complains that there is "no matching function for call to 'Child::Child(< brace-enclosed initializer list>)". I assume this error happens because Child, since it has a base class, is no longer an aggregate (although it is still a POD).

I would like to avoid manually creating a constructor for Child, and just use braced initialization. I also need Child to directly contain all the members in Parent. In other words, having Child encapsulate Parent wouldn't work. So my main question is, is there a way to use braced initialization with a child class?

Aucun commentaire:

Enregistrer un commentaire