user269597
user269597

Reputation:

Aggregate initialization of a class that privately inherits an aggregate class in C++11

Consider the following code:

struct base
{
    int x, y, z;
};

struct derived : private base
{
    using base::base;
};

int main(int argc, const char *argv[])
{
    base b{1, 2, 3}; // Allowed
    derived d{1, 2, 3}; // Not allowed
}

The line derived d{1, 2, 3}; makes my compiler (Clang 3.3) fail with error "no matching constructor for initialization of 'derived'". Why is this? Is there any way to initialize derived via aggregate initialization?

Upvotes: 1

Views: 1049

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490728

derived has a base class, so it's not an aggregate (§8.5.1/1: "An aggregate is an array or a class (Clause 9) with [...] no base classes [...]").

Since it's not an aggregate, it can't be initialized with aggregate initialization.

The most obvious workaround would probably be to add a ctor to base, and have the ctor for derived pass arguments through to base:

struct base
{
    int x, y, z;

    base(int x, int y, int z) : x(x), y(y), z(z) {}
};

struct derived : private base
{
    derived(int a, int b, int c) : base(a, b, c) {}
};

int main(int argc, const char *argv[])
{
    base b{1, 2, 3}; // Allowed
    derived d{1, 2, 3}; // Allowed
}

Of course, that doesn't work if you're set on base remaining an aggregate.

Edit: For the edited question, I don't see a way to use an std::initializer_list here -- std::array doesn't have anything to accept an initializer_list.

Upvotes: 9

Related Questions