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.

1
  • 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?
    – Eddy
    Commented Oct 9, 2019 at 11:35
0

Use a constant expression constexpr

In the header Rules.h file:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.