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 functionRules::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() { }