Takarakaka
Takarakaka

Reputation: 279

C2864 compiler error

I am making some game and I get following error :

class Apple:public Fruit{
public:
    bool isAppleOK = false;
Apple(int amount, int pHValue) {
    amount = amount;
    pHValue= pHValue;
} ~Apple() {
}
    /*code trimmed*/

error C2864: 'Apple::isAppleOK ' : only static const integral data members can be initialized within a class

What am I missing here?

Upvotes: 4

Views: 7032

Answers (3)

coelhudo
coelhudo

Reputation: 5090

You cannot initialize a variable inside declaration.

class Apple: public Fruit{
public:
    bool isAppleOK;
    Apple(int amount, int pHValue) : amount(amount), pHValue(pHValue),
                                     isAppleOK(false)
    {
    } 

    ~Apple() {
    }
};

It is not totally related, but also use initialization list, because your compiler maybe will translate:

class Apple:public Fruit{
public:
    bool isAppleOK;
    Apple(int amount, int pHValue) {
    amount = amount;
    pHValue= pHValue;
    } 
    ~Apple() {
    }
};

To

class Apple:public Fruit{
    public:
        bool isAppleOK;
        Apple(int amount, int pHValue): amount(), phValue(), 
                                        isAppleOk() {
        amount = amount;
        pHValue= pHValue;
        } 
        ~Apple() {
        }
    };

If you have complex types as parameters in your constructor maybe will occur some overhead in each object construction, because first the class member will be initialized, after that it will be assign to a new value.

With initialization lists this will be done at the same time without the possible overhead.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

This is not the way you initialize member variables in C++. You need to set the value in the init list of the constructor:

Apple(int amount, int pHValue) : isAppleOK(false) {
    amount = amount;
    pHValue= pHValue;
}

You can also move the initialization of your other variables into the initialization list:

Apple(int amt, int pHv)
:   isAppleOK(false)
,   amount(amt)
,   pHValue(pHv) {
}

Upvotes: 11

Ed Swangren
Ed Swangren

Reputation: 124790

What am I missing here?

You're missing this:

only static const integral data members can be initialized within a class

Is isAppleOk a static const intergral member of Apple? No, it's not. Initialize it in your constructor's initialization list.

class Apple {
public:
    Apple() : isAppleOk(false) { }
private:
    bool isAppleOk;
}

Upvotes: 6

Related Questions