Adnan Zahid
Adnan Zahid

Reputation: 583

Include dependency

I have a PieceStrategy class:

#include "QueenStrategy.cpp"
class PieceStrategy {
    void promoteToQueen() {
        this = new QueenStrategy();
    }
}

And I have a QueenStrategy class which inherits from it:

#include "PieceStrategy.cpp"
class QueenStrategy : public PieceStrategy {}

Now arises the circular includes problem. But in this case, I cannot use forward declaration.

What should I do?

Upvotes: 1

Views: 55

Answers (1)

hansmaad
hansmaad

Reputation: 18915

  1. You should not include cpp files, but headers
  2. You must not assign to this
  3. Choose another design. You should not try to modify the strategy but select another one for the actual object, that uses that strategy.

piece.hpp

#include "strategy.hpp"
class Piece
{
    std::unique_ptr<Strategy> strategy;
public:
    static Piece Pawn();
    void PromoteToQueen();
};

piece.cpp

#include "pawn.hpp"
#include "queen.hpp"

Piece Piece::Pawn()
{
    Piece p;
    p.strategy = std::make_unique<PawnStrategy>();
    return p;
}

void Piece::PromoteToQueen()
{
    strategy = std::make_unique<QueenStrategy>();
}

Upvotes: 4

Related Questions