Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass inherited arguments to base class constructor, then do something in derived class constructor

Tags:

c++

c++11

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.

like image 300
Simon Avatar asked Nov 15 '25 19:11

Simon


1 Answers

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
    }
};
like image 179
NathanOliver Avatar answered Nov 18 '25 09:11

NathanOliver