I'm trying to make a program inspired from the chess game to develop a working understanding of classes interaction, inheritance, etc..
The way I want it to work is:
-board class, that is basically a class piece pointer matrix. if a piece exists in the square, map[x][y] = &piece; else map[x][y] = NULL;
-piece class, that knows it's own coordinates and where it wants to go.
The problem is at class pion::move (lines 69 -- 81),I get this sort of errors: "sah_minimal.cpp:71:16: error: invalid use of incomplete type 'struct board'" Defining piece and pion after the board class definition would be useless because I have a circular dependency.
You need to separate the class definition from the function bodies. Typically this is done by putting classes in headers and the function bodies in separate cpp files.
Specifically, in pion, the body of the functions that use board must come after the board definition. This an easily be accomplished like so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// pion.h
#include "piece.h"
class pion: public piece
{
//~ char a; -- this works?!?!
public:
pion();
// ~pion(); (no need for a dtor if it's empty)
bool move ();
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// pion.cpp
#include "pion.h"
#include "board.h" // now board is fully defined
pion::pion()
{
// body goes here
}
bool pion::move()
{
// body goes here. Now you can use board and it's fine
}
Thank you for your reply, Disch.
I've read your article and several more on the subject of header files. However I still can't get my code to run; please help me solve it.
I'm almost sure that the trouble is with the way the includes are done, but i've had no success with different ways of include ( eg. in sah_class_piece.cpp include sah_class_board.h and sah_class_piece.h and in main include only sah_class_piece.cpp).
With the following layout, I get "undefined reference" to almost all class member functions.
sah_class_board.cpp need to #include sah_class_pieces.h because it is using the piece class.
sah_class_pieces.cpp might have to #include sah_class_board.h ... but I'm not sure. It doesn't look like Piece is dereferencing board anywhere so maybe it's not necessary.
The code is working provided I included booth headers in all cpps, and the circular dependency is functional.
The problem was that I didn't compile the files properly (the IDE was trying to compile them separately).
Corect compilation and execution is:
$g++ -c *.cpp
$g++ -o a.out *.o
$./a.out
I can't thank you enough, Disch, I wouldn't have trusted my code enough to look to problems elsewhere whitout your guidance.