Home > database >  C header file class declaration
C header file class declaration

Time:10-03

So in my C project, I have my "cards.h" and "cards.cpp" file, and the "cards.h" file declares 3 classes: Card, Deck, Hand

class Card {
 private:
       // some private attributes
 public:
       // some public methods
       //.....

       void play(Deck& deck, Hand& hand); // This method plays the card, removes it from the hand, and places it in the deck 
}

class Deck {
private:
       vector<Card> deckCards;
public:
       // some public methods
}

class Hand {
private:
       vector<Card> handCards;
public:
       // some public methods
}

The compiler gives me an error in the play method on "Deck" and "Hand" with the error "Unknown type name Deck", "Unknown type name Hand". How can it not see the classes that are declared in the same .h file? Does C read the file from top to bottom ?

  • I also can't put the Card class at the bottom, because Deck and Hand uses Card
  • I have to put all 3 classes in the same file, the "cards.h" file.

CodePudding user response:

You are correct. C needs the declarations to go from top to bottom. A side note you have incorrect syntax for the class declarations. Each class needs to be terminated with a colon after the last closing curly brace. I tested your example and it works fine.

You can separate the classes into their own files and use forward class declarations since each class needs the other. Or you can leave them in the same file and add the forward class declaration prior to usage. Like below.

#include <vector>
using namespace std;

class Deck;
class Hand;

class Card {
private:
    // some private attributes
public:
    // some public methods
    //.....

    void play(Deck& deck, Hand& hand) {}; // This method plays the card, removes it from the hand, and places it in the deck 
};

class Deck {
private:
    vector<Card> deckCards;
public:
    // some public methods
};

class Hand {
private:
    vector<Card> handCards;
public:
    // some public methods
};
  • Related