José Otero José Otero -4 years ago 86
C++ Question

C++: How to specify array length with a static constant variable?

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 and 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?

Answer Source

Try this:

#include <array>

class A {
 public:
  static const size_t LENGTH = 12;
 private:
  std::array<int,LENGTH> internalArray;
};

int main(){
  A a;
}

You can declare the value of LENGTH right in your class header, no need to have it be a separate global variable or for it to live in the cpp file.

Use the size_t type, since that is what the std::array template expects.

If that public/private arrangement is bad for you, know that you can include multiple public/private indicators in the class header.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download