KarimS
KarimS

Reputation: 3902

static const class member as initializer to member array

class sarray
{
public:
    static const unsigned int iarr_size;

    void add(const char c ) {}

private :   
    unsigned char iarr[iarr_size];
    unsigned int off;

public 

};

Why do unsigned char iarr[iarr_size] give me a not constant expression error for iarr_size??

iarr_size is declared as const.

Sorry for my bad english.

Upvotes: 2

Views: 44

Answers (1)

Benny Isaacs
Benny Isaacs

Reputation: 105

You should initialize iarr_size with an unsigned int. For example:

class sarray
{
public:
    static const unsigned int iarr_size = 5;

    void add(const char c ) {}

private :   
    unsigned char iarr[iarr_size];
    unsigned int off;

public 

};

The better solution is that the member iarr will be a pointer to unsigned char, and in the constructor use new to allocate the array:

class sarray
{
public:
    sarray()
    {
        int i = 5; // any int
        iarr = new unsigned char[i];
    }
    void add(const char c) {}

private:
    unsigned char* iarr;
    unsigned int off;
};

Upvotes: 3

Related Questions