Search code examples
c++constructor

How to delegate to differnt constructor of a base class and call a derived class constructor?


I have this sample code:

#include <iostream>

class A
{
public:
    A()
    {
        std::cout << "Default constructor of A" << '\n';
    }
    A(int i)
    {
        std::cout << "Inside the constructor of A with one int argument" << '\n';
    }
    A(double i)
    {
        std::cout << "Inside the constructor of A with one double argument" << '\n';
    }
};

class B : A
{
    using A::A;
public:
    B()
    {
        std::cout << "Default constructor of B" << '\n';
    }
};

int main()
{
    B b(12);

    std::cout << "End of main";
}

And the output is :

Inside the constructor of A with one int argument
End of main

I understand why Bs constructor is not called (see Constructor inheritance in C++. Derived class's default constructor is not being called) and I can write a B(int), but the thing is that A has many constructors and when constructing a B I want the corresponding A constructor be called and one specific B constructor.

How can I achieve this without writing one B constructor for each A constructor?

In other words, I want output of B b(12) to be

Inside the constructor of A with one int argument
Default constructor of B
End of main

and also B b(4.2) to be

Inside the constructor of A with one double argument
Default constructor of B
End of main

without rewriting the constructor of B many times.


Solution

  • How can I achieve this without writing one B constructor for each A constructor?

    Instead of doing the work directly in B, you might add extra base/member which would do the job:

    struct B_impl
    {
        B_impl()
        {
            std::cout << "Default constructor of B" << '\n'; // B_impl currently ;-)
        }
    };
    

    And then either

    class B1 : A, B_impl
    {
        using A::A;
    };
    

    or

    class B2 : A
    {
        using A::A;
        B_impl b_impl{};
    };
    

    Demo