Search code examples
c++c++14aggregate-initialization

Aggregate initialization pre-C++17


Consider the following class hierarchy, made from aggregates:

struct Foo {
    int k;
    double d;
};

struct Bar : Foo {
    int i;
};

Now, let's say I would like to initialize an object of type Bar from an object of type Foo, giving extra argument for i. (For reason to dull to discuss here, adding a constructor to Bar which accept Foo and int, or modifying definition of Bar or Foo in any other way is out of question). In C++17 I would use aggregate initialization:

auto make(const Foo& f) {
    return Bar{f, 42};
}

This is not available in C++14. Is there anything else I can do mimic desired behavior in C++14? I am trying to avoid something like

auto make(const Foo& f) {
    Bar b;
    b.k = f.k;
    b.d = f.d;
    b.i = 42;
    return b; // or return Bar{f.k, f.d, 42};
}

Where the thing I am trying to avoid is making make aware of internals of Foo - i.e. make is fine to know how to initialize extra members of Bar, but would prefer not to initialize members of Bar which are common with Foo.


Solution

  • auto make(const Foo& f) {
      Bar b;
      static_cast<Foo&>(b) = f;
      b.i = 42;
      return b;
    }