const variable inside of a declaration of a class...

closed account (jvqpDjzh)
/*
declaration of class...
*/

#ifndef DECKOFCARDS_H
#define DECKOFCARDS_H

class DeckOfCards
{
public:
const int SEEDS = 4;//can I declare here a const?
const int FACES = 13;//non-static data member available only with std c++11//what is the solution?Why?


DeckOfCards();
~DeckOfCards();
void printA(const int deck[SEEDS][FACES]);
void distribute(const int deck[SEEDS][FACES], const char** seeds, const char** faces);
void mix(int deck[SEEDS][FACES]);
};

#endif
Why?
Because initialization non-static constant members in class declaration wasn't allowed before C++11.
what is the solution?
Compile in C++11 mode. Or move value initialization to the class definition or constructor. Or make variable static, it will fix errors with your functions as well.
closed account (jvqpDjzh)
When do we have to use static members within a class in C++? (In JAVA is more understandable:)

if I use them as static what happen is this (in the main.cpp):

/**********************************************************************/
#include "DeckOfCards.h"

int main()
{
DeckOfCards* deck52 = new DeckOfCards();//deck52 is declared!

int deck[deck52::SEEDS][deck52::FACES] = {{0}};//deck52 is not a class or a namespace...

const char* seeds[deck52::SEEDS] = {"Hearts", "Diamonds", "Clubs", "Spades"};
const char* faces[deck52::FACES] = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};

deck52->mix(deck);
cout<<"Mixing the cards...";
cin.get();

cout<<"\nThese are the cards:\n\n";
deck52->distribute(deck, seeds, faces);

return 0;
}
Last edited on
DeckOfCards::SEEDS ← use class name, not variable name.
closed account (jvqpDjzh)
Thank you very much!!!
I didn't know we have to do so, I thought was more reasonable do like I did: accessing through the object and not the class directly...
This is just for const variables or what?
Last edited on
This is just for const variables or what?

It's also true of static methods.

In C++, when a class member (data or function) is declared as static, it means that there is one single instance of that member that is shared between all instances of the class. Those static members exist independently of any particular instance of the class. In fact, they exist and can be used, even if no objects of that class have been instantiated!

That's why you access them using the name of the class, not the name of a specific object.

As you might imagine, the rules for how you define and use static members are different from those for non-static members. But that's something you can look up - I'm not going to re-write a textbook here :)
Last edited on
Topic archived. No new replies allowed.