mardi 4 avril 2017

How to initialize derived class members when using C++11 inheriting constructors?

There's something I don't understand about the new C++11 feature of inheriting the base class's constructors with:

using BaseClass::BaseClass;

I thought this was a handy feature, but now I have a derived class that has additional members, and it seems I have to rewrite the constructor if I want to initialise the derived class's members:

struct BaseClass
{
    BaseClass(char* name, int intVal, float floatVal) : name(name), intVal(intVal), floatVal(floatVal) {}
    char* name;
    int intVal;
    float floatVal;
};

struct DerivedClass : BaseClass
{
    using BaseClass::BaseClass;
    int additionalMember;
};

Do I have to manually rewrite the constructor and pass the values to the base's constructor, then initialise the additional member?

struct DerivedClass : BaseClass
    {
        DerivedClass(char* name, int intVal, float floatVal) : BaseClass(name, intVal, floatVal), additionalMember(7) {}
        int additionalMember;
    };

If so, the use of this new feature of inheriting constructors seems really limited.

So do I have to rewrite the constructors each time?

Aucun commentaire:

Enregistrer un commentaire