4

Consider the following:

I derive a class Child from another class Parent. Parent has a ton of overloaded constructors. The Child class does not need any more parameters for construction. But once the base class constructor has been called, I want to do some more stuff during object construction.

So my question is: Using Modern C++, can I write a single constructor that accepts all arguments that any of the overloaded base class constructors accept and just forwards them to the respective one?

To be explicit: I am aware of the using Parent::Parent syntax, but that would not give me the opportunity to do anything after the base class constructor is called, as far as I understand.

I have searched around here on SO and in the depths of the internet, but I could not find anything like that, even though it seems like a fairly common use case to me. Any help would be much appreciated.

Simon
  • 405
  • 2
  • 8

1 Answers1

8

One way you could do this is to make a variadic template constructor in the derived class that passes all of its arguments to the base class. Then you can do whatever additional stuff you want in the body of that constructor. That would look like

struct Base
{
    Base (int) {}
    Base(int, int) {}
    //...
};

struct Derived : Base
{
    template<typename... Args>
    Derived(Args&&... args) : Base(std::forward<Args>(args)...) // <- forward all arguments to the base class
    {
        // additional stuff here
    }
};
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 2
    It could be made conditonally `explicit`, if `Base` has both explicit and non-explicit constructors. – HolyBlackCat Jul 27 '20 at 20:45
  • Perfect, thank you. I had read about variadic template constructor but I somehow thought this would only be for templated classes. I guess, I was wrong. – Simon Jul 28 '20 at 06:04
  • @HolyBlackCat, given that not only single-argument constructors can be explicit, that's a tricky one, since we then cannot use is_convertible to test for implicit conversion in such cases – Alex Vask Feb 04 '22 at 21:22