Reputation: 47
I'm writing a card games program. I have go fish written in its own files (header and implementation files), and I now want to be able to access go fish from a card games class.
Go fish inherits from the card game class, as it contains things like the list of players and deck of cards. Additionally, the card games header defines the card struct.
So I #include the card game file in my go fish file. But now what I want to do is to simply #include the card game file in my driver program and access go fish from that (I'll be adding poker later).
The problem is that I can't #include the go fish file in the card game class because that would cause an infinite inclusion error.
Here's some example code to get the gist:
//card_games.h
class card_game{...};
//gofish.h
#include "card_games.h"
class gofish : public card_game{...};
And here's what I want to do:
//main.cpp
#include "card_games.h"
//main function
{
card_game *game;
game = new gofish;
}
But in main, it doesn't recognize gofish as a class. So how should I go about this?
Upvotes: 0
Views: 306
Reputation: 138
#ifndef HEADERNAME_H_
#define HEADERNAME_H_
...
#endif // HEADERNAME_H_
Upvotes: 0
Reputation: 3153
#include "gofish.h"
This you do above your main(). That way you can have access to both classes gofish and card_game. I do agree that this is very coupled as well. You should separate them more and not make them so coupled. There are many ways to go about it. Depends how complex your code is going to be.
Upvotes: 0
Reputation: 206577
I can think of the following options.
In main.cpp
add #include "gofish.h"
. When you want to your program to play poker, add #include "poker.h"
to main.cpp
.
Implement a factory pattern where you could get handle to a card_game*
by using a string. Then, add a virtual function play
. When you call play
on the object returned by the factory, the call will be directed to the right game.
Upvotes: 0
Reputation: 47
Here's what I did.
Removed base class's knowledge of gofish.
I made a new file (games.h) to include gofish.h and included that in my main file. The reason I did this is because I will be adding another game, and as this is for an assignment, the idea is that I might add a lot more games.
Now with this, I can include cardgame.h in my gofish.h and get gofish from games.h
Thanks everyone for the help.
Upvotes: 0
Reputation: 962
Include gofish.h at bottom of file card_games.h, then you will need to include only card_games.h above main().
Upvotes: 0
Reputation: 9211
You need to include the gofish file in main.cpp
#include "gofish.h"
main needs to know about it before you can create one within main.
Upvotes: 2