Reputation: 14434
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?
Upvotes: 3
Views: 317
Reputation: 4106
You could use default value:
struct DerivedClass : BaseClass
{
using BaseClass::BaseClass;
int additionalMember = 0;
};
However if you need the value passed from the user of your class you will have to provide the constructor for DerviedClass
.
Upvotes: 3