Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting an error when declaring a variable in a class declaration within a header?

I'm trying to make a class that has a simple integer with in it. Of course, it uses header files and whatnot.

Here's the code:

class.h

 class consolBuf
{
private:
    int buffersize1 = 10; //Data member initializer is not allowed
    int buffersize2 = 10;
    static char screenBuffer[10][10]; //screenBuffer
public:
    consolBuf(void);
    ~consolBuf(void);
    void draw();
    void write(int x, int y);
    char get(int x, int y);
};

For some reason some reson Visual Studio keeps complaining that I can't declare a integer in the class.h. I've searched everywhere and I can't find an answer. Is there something I'm missing?

like image 223
ILikePizza555 Avatar asked Nov 17 '25 06:11

ILikePizza555


2 Answers

Indeed you can't initialize members like that. If you wanted to initialize those as default values for each instance, you would do that in the constructor:

consolBuf::consolBuf()
    : buffersize1(10)
    , buffersize2(10)
{

}
like image 95
Mysticial Avatar answered Nov 19 '25 20:11

Mysticial


In C++03, only static constant values can be defined inside the class. But then, it seems that this is what you need anyway in your case:

class consolBuf
{
private:
    static int const buffersize1 = 10; //Data member initializer is now allowed
    static int const buffersize2 = 10;
    static char screenBuffer[buffersize1][buffersize2]; //screenBuffer
public:
    consolBuf(void);
    ~consolBuf(void);
    void draw();
    void write(int x, int y);
    char get(int x, int y);
};

Note that in C++11, your original code is allowed. So if your original code is really what you wanted, all you might have to do is to enable C++11 features. In C++03, you'll have to use member inizializers in the constructor instead.

like image 23
celtschk Avatar answered Nov 19 '25 20:11

celtschk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!