3

Consider following code:

struct Base //in my real scenario Base class can not be changed
{
    int a;
    double b[10];
};

struct Child : Base
{
    Child(int aa, double bb[10]) : Base{aa} {}     //This works fine
    Child(int aa, double bb[10]) : Base{aa, bb} {} //this is not working
};

The second constructor of child is not working. I get the error "array must be initialized with a brace-enclosed initializer". How can I initialize b in Child without changing Base class (for example using vector instead of c-like array, i am not allowed to do that)

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Gaetan
  • 577
  • 2
  • 7
  • 20

1 Answers1

6

In Child's constructor, bb is not an array: because of decay, it's just a pointer. And you can't initialize an array (b in Base) with a pointer.

Using std::array in both classes instead of raw arrays would solve your problem:

struct Base
{
    int a;
    std::array<double, 10> b;
};

struct Child : Base
{
    Child(int aa, std::array<double, 10> bb) : Base{aa, bb} {}
};

However, since you mention that Base cannot be modified, you will have to copy the elements manually (in the general case, you can also move them, although there is no point with fundamental types):

#include <array>
#include <algorithm>
#include <iostream>

struct Base {
    int a;
    double b[10];
};

struct Child : Base {
    Child(int aa, std::array<double, 10> bb) : Base{aa} {
        std::copy(bb.begin(), bb.end(), b);
    }
};

int main() {
    auto child = Child(3, {2, 3, 4});

    for (auto it : child.b) {
        std::cout << it << " ";
    }
}

Live on Coliru

You can also do that using a reference instead of std::array, but the syntax is a bit convoluted:

Child(int aa, double const (&bb)[10]) : Base{aa} {
    std::copy(&bb[0], &bb[10], b);
}
Nelfeal
  • 12,593
  • 1
  • 20
  • 39