Static const data member of a class as a size of a member array of the same class?

Viewed 52

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 ;
1 Answers

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;
Related