M Towseef Hossain
M Towseef Hossain

Reputation: 9

Circular dependency issues with inherited classes

//grid.h
class Grid {
    ...
    std::vector<std::vector<Tile>> theBoard;
    ..
}
//tile.h
class Tile {
    ...
    Piece *piece;
    ...
}
//piece.h
class Piece {
    ...
    Grid *theBoard;
    ...
}
//queen.h
class Queen : public Piece {
    ...
}

We're running into linking dependency issues when we try to compile this. How do we write the include headers/forward declarations to support this?

Upvotes: 0

Views: 70

Answers (2)

DasElias
DasElias

Reputation: 569

In Piece.h, you can forward declare the Grid-class. Forward declaration means, that you tell the computer, that a particular type exists, but it doesn't know anything about its size or members yet. You can't forward declare in Queen.h, since you're not allowed to inherit from a forward declared class. Furthermore, you aren't allowed to store a forward declarated class as a member, you can only store a pointer or reference to them.

//piece.h
// forward declaration of Grid
class Grid;

class Piece {
    ...
    Grid *theBoard;
    ...
}

Please note that in the implementation file of piece.h, you need to include grid.h so that the compiler can know which methods can be called on Grid, but since this #include is in the implementation file, you won't get a circular dependency.

Upvotes: 1

Derek C.
Derek C.

Reputation: 998

Typically when you have circular dependencies it means you need to rethink your structure. In your case perhaps that "does a piece really need to know about the board?".

The other solution is to forward declare a class. You would do this by writing :

class a;

And this simply tells the compiler "hey, a exists, it's coming later". This can become messy very quick so it's likely better to try and rethink your structure so that your classes are more self contained and don't depend on each other as much.

Upvotes: 1

Related Questions