0

I am about to learn basic OOP operations in C++ and now I encountered a problem with static members of class. I try to build simple card game. I create classes Rules, Deck and Card.

My Deck class taking rules and some constants from Rules class and then do something. I'm only use Deck::createDeck(); in main function, nothing else. When I try to compile the code I get in result error:

/usr/bin/ld: CMakeFiles/CardGame.dir/Sources/Rules.cpp.o: in function Rules::getSuits[abi:cxx11]()': /home/bartosz/CLionProjects/CardGame/Sources/Rules.cpp:12: undefined reference toRules::suits[abi:cxx11]' /usr/bin/ld: CMakeFiles/CardGame.dir/Sources/Rules.cpp.o: in function Rules::getRanks[abi:cxx11]()': /home/bartosz/CLionProjects/CardGame/Sources/Rules.cpp:16: undefined reference toRules::ranks[abi:cxx11]' collect2: error: ld returned 1 exit status

But I belive that static members (suits and ranks) are corectlly initialized, so why compiler doesn't see this variables?

My code:

Rules.h

#ifndef CARDGAME_RULES_H #define CARDGAME_RULES_H #include <string> class Rules { public: static std::string suits[4]; static std::string ranks[13]; public: static std::string * getSuits(); static std::string * getRanks(); }; #endif //CARDGAME_RULES_H 

Rules.cpp

#include "../Headers/Rules.h" std::string suits[4] = {"Diamonds", "Hearts", "Spades", "Clubs"}; std::string ranks[13] = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; std::string * Rules::getSuits() { return suits; } std::string * Rules::getRanks() { return ranks; } 

Deck.h

#ifndef CARDGAME_DECK_H #define CARDGAME_DECK_H #include "Card.h" class Deck { private: Card * cards; Deck(); public: static void createDeck(); void shuffle(); void dealCards(); }; #endif //CARDGAME_DECK_H 

Deck.cpp

#include "../Headers/Deck.h" #include "../Headers/Rules.h" Deck::Deck() { } void Deck::createDeck() { std::string * ranks = Rules::getRanks(); std::string * suits = Rules::getSuits(); // some operations } void Deck::shuffle() { } void Deck::dealCards() { } 

2 Answers 2

3

In Rules.cpp, you don't define the static members Rules::suits and Rules::ranks, but rather introduce 2 new global variables.

In order for the static definition to work, you need to specify the fully qualified name, e.g. Rules::suits.

Sign up to request clarification or add additional context in comments.

1 Comment

Like this: std::string Rules::suits[4] = {"Diamonds", "Hearts", "Spades", "Clubs"}; std::string Rules::ranks[13] = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; right?
0

Use a constant expression constexpr

In the header Rules.h file:

constexpr std::array<std::string_view, 4> suits = {"Diamonds", "Hearts", "Spades", "Clubs"}; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.