Search code examples
c++c++11inheritanceconstructorinitialization-list

How do I use an initialization list with a base class?


Given the following:

struct A
{
    int foo;
    int bar;
};

struct B : public A
{
    int baz;
};

How would I construct a B with an initialization list that also constructs the elements in A? The following does not seem to work, but I am looking for something like:

B my_b{{1, 2}, 3}; // foo = 1, bar = 2, baz = 3

Solution

  • You can't do it without adding an explicit constructor and doing much of the work yourself:

    struct B : public A
    {
      B(const A &a, int _baz) : A{a}, baz{_baz} {}
      int baz;
    };
    
    B my_b{{1, 2}, 3};
    

    And you'll have to keep that container in sync with B's members.

    If you had used containment instead of inheritance, then B would still be an aggregate and therefore you could use aggregate initialization.