2

I am making List class through fixed sized arrays. I want to declare ARRAY_SIZE within the class as a static const data member therefore my class is self contained and also I can use it as a size of an array in array declaration in the same class. But I am getting error that "array bound is not an integer constant before ']' "

I know I can use the statement as global variable like const int LIST_SIZE = 5 ;

but I want to make it as static const data member of a class.

class List
{
public :
    List() ; //createList
    void insert(int x , int listIndex) ;
    void removeIndex(int listIndex) ; //index based remove
    void removeValue(int listValue) ; //value based remove
    void removeAll() ;
    int find(int x) ;
    void copy(List *listToCopy) ;
    void update(int x , int index) ;
    bool isEmpty() ;
    bool isFull() ;
    int get(int index) ;
    int sizeOfList() ;
    void printList() ;

private :
    //int translate ( int position ) ;
    static const int LIST_SIZE ;
    int items[LIST_SIZE] ;
    int current ;
    int size ;
} ;
//********** END OF DECLARATION OF LIST CLASS **********//

//Definition of static data member of LIST
const int List::LIST_SIZE = 5 ;
SANG
  • 31
  • 1

1 Answers1

0

The error message is self explicit. In C++ language the size of a plain raw array or of a std::array has to be a (compile time or constexpr) constant. The modifyer const is only a promise you are making to the compiler that the value will never change, but it is not enough to make the variable useable where only a true constant can be.

The magic word in constexpr:

    ...
    static const constexpr int LIST_SIZE = 5;
    int items[LIST_SIZE];
    int current;
    int size;
};
//********** END OF DECLARATION OF LIST CLASS **********//

//Definition of static data member of LIST
const int List::LIST_SIZE;
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • is the const keyword required in `static const constexpr int LIST_SIZE = 5;` ? and also is the external definition `const int List::LIST_SIZE;` required? I am asking as my code is running without const keyword and external definition. – SANG Oct 11 '21 at 07:12
  • @SANG: You declared it `const` and defined it later and I didn't want to remove either. `const` should be implied by `constexpr` so it is useless. The external definition is only required if `List::LIST_SIZE` is ODR used, broadly speaking if you use its address for example for a pointer or reference. – Serge Ballesta Oct 11 '21 at 07:23