-3

I can easily declare and initialize a constant array member in a header file like so:

class MyClass {
 public:
  const int arr[4] = {1, 2, 3, 4};
}

But when the data is defined by a function, I cannot initialize it in the header:

#include <cmath>
#define BASE 2
class MyClass {
 public:
  const int arr[4];
  for (i=0;i<4;i++) {
        arr[i] = pow(BASE, i);
  }
}

When I try to initialize the array in the class constructor in the .cpp file, I get the obvious uninitialized member with 'const' typeerror, as the array should already be initialized.

How can I initialize a const int array in the header file with a preprocessor macro and cmath functions?

uzumaki
  • 1,743
  • 17
  • 32

2 Answers2

4

It's possible to use BOOST_PP_REPEAT, if your array can have at most 256 elements (fewer if you're stuck with MSVC). Something like:

#define my_elem(z, n, data) pow(BASE, n)

const int data[4] = {BOOST_PP_REPEAT(4, my_elem, "ignored - extra data not needed")};

But you should really, really, ask yourself why you need a non-static butconst member variable, since that is almost never a useful thing to do, and places major limitations on what your program can do (e.g. it deletes the assignment operator).

o11c
  • 15,265
  • 4
  • 50
  • 75
0

You can do something like this (if the array is not too long):

#include <iostream>
#include <cmath>
#include <functional>

constexpr int BASE = 2;

class A {
public:

    A(std::function<int(int)> f);

    const int arr[4];
};

A::A(std::function<int(int)> f) :
    arr{ f(1),f(2), f(3), f(4) }
{
}

int main() {
    auto f = [](int i) { return pow(BASE, i); };
    A a(f);
    for (const auto val : a.arr) {
        std::cout << val << std::endl;
    }
    return 0;
}
Yuval Ben-Arie
  • 1,280
  • 9
  • 14