samedi 27 janvier 2018

Can I inherit a constructor in C++11 and initialise something extra without having to rewrite the constructor?

I was happy to find out that in C++11 we can inherit constructors like:

class Foo
{public:
    Foo(int a, double b, std::string name, char somethingElse);
};

class Derived : public Foo
{public:
    using Foo::Foo;
};

But I'm finding that I'm often extending the base class where there might be maybe one or two extra features, and I need to initialise a couple extra members by maybe passing as extra argument or something. In this case is seems I have to rewrite the constructor and pass all the arguments to the base one. I'm wondering if there is a better solution. I thought maybe just using the inherited constructor and then initialising the extra member on the next line after construction, but it doesn't seem right:

Derived d = Derived(6, 6.0, "name", 'a');
d.extraMember = 4;
d.funcptr = &somefunction;

I figured it was an excellent feature but then I realised more and more that my extended classes needed extra initialisation info.

Aucun commentaire:

Enregistrer un commentaire