Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance error: "expected class-name before '{' token"

I am writing a poker program, where two classes I have are a Deck class and a Hand class. The Hand class inherits from the Deck class, so it can use its printGroup method. However, when I compile I get an error that says:

expected class-name before '{' token

referring to the line:

 class Hand : public Deck{  

Here is the code for the two class headers. Could anyone help me solve this?

//Hand header

#ifndef HAND_H
#define HAND_H

#include <iostream>
#include <vector>
#include "Deck.h"
#include "Card.h"

class Card;

class Hand : public Deck{    //error occurs from this line
public:
    Hand(){}
    void createHand(std::vector<Card> &, std::vector<Card> &);
};


#endif /* HAND_H */

//Deck header

#ifndef DECK_H
#define DECK_H

#include <iostream>
#include <vector>
#include "Card.h"

class Card;

class Deck{
public:
    Deck(){}
    void createDeck(std::vector<Card> &);
    void printGroup(std::vector<Card> &, int);
    void sortDeck(std::vector<Card> &, int, int);
};

#endif /* DECK_H */
like image 244
alchemist_faust Avatar asked Jul 15 '26 03:07

alchemist_faust


1 Answers

Assuming that @marcog's gut feeling that it is a circular dependency is correct (maybe Card.h includes Hand.h, thereby importing the file Hand.h before getting up to the declaration of the Deck class), this can be solved by forward declarations.

I see you already have a forward declaration of the Card class ("class Card;"). Therefore, do you really need to #include "Card.h"? If you remove that include, you can still refer to the class Card due to the forward declaration, but it may resolve the cyclic dependency.

I usually don't #include .h files from other .h files in C++ unless I really have to. If you are just referring to a class in another file (by pointer, reference, or putting it in a container like vector), then you can get away with just forward-declaring the class, and physically including the header file from the .cpp file only.

like image 121
mgiuca Avatar answered Jul 17 '26 17:07

mgiuca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!