I want to declare the length of an array member variable using a constant static variable of the class. If I do:
// A.h
#include <array>
using namespace std;
class A {
array<int,LENGTH> internalArray;
public:
const static int LENGTH;
};
// A.cpp
#include "A.h"
constexpr int A::LENGTH{10};
There is the error in A.h: "'LENGTH' was not declared in this scope", when declaring internalArray.
I find it weird because how come a class member variable, i.e. LENGTH, is out of scope inside the class? The only workaround I found was to move the initialization from A.cpp to A.h:
// A.h
#include <array>
using namespace std;
constexpr int LENGTH{10};
class A {
array<int,LENGTH> internalArray;
public:
const static int LENGTH;
};
But as I understand, first these are two different variables: the global namespace scope LENGTH and the class scope LENGTH. Also, declaring a variable in .h (outside class A) will create an independent LENGTH object in every translation unit where the header is included.
Is there a way to specify the length of the array with a static class-scoped variable?
LENGTHis below first usage of it.LENGTHdefined in the header (and above the definition of the array); without it, the size of an instance ofAis unavailable to anyone exceptA.cpp, which makes it impossible for anyone else to instantiate your class (how do they know how much memory to reserve for an instance otherwise?). Have you tried defining it per the guidelines here? That's for C-style arrays, but it's the same idea; you need to have a defined value forLENGTHto use it as a compile-time constant.