0

Here is my BoardField.h:

#pragma once

#include "ChessPiece.h"
#include "Game.h"
#include <SDL.h>

class BoardField{
private:
    ChessPiece m_piece;
    SDL_Rect m_field;

public:

    friend class Game;
};

And Game.h

#pragma once

#include "BoardField.h"

class Game {
private:
    //members
    BoardField* m_board_fields; // 16th line
    ...

    //methods
    ...
public:
    ...
};

And I'm getting these errors in VS2017 when trying to compile :

Error

Where is the problem? Even tried to create new project it doesn't work anyway.

Faustas Butkus
  • 291
  • 1
  • 5
  • 14
  • which line is line 16? I presume the second block of code is game.h? does the error occur if you compile just the code you posted? – Alan Birtles Mar 03 '18 at 18:24
  • 4
    `BoardField.h` includes `Game.h` which includes `BoardField.h`. `BoardField` depends on `Game` which depends on `BoardField` which depends on `Game` which... And so on forever. One of the classes will be used before it is declared. Do some research about *circular inclusion* and *circular dependencies* and *forward declarations*. – Some programmer dude Mar 03 '18 at 18:25
  • @Someprogrammerdude how to avoid it and be able to make class a friend? – Faustas Butkus Mar 03 '18 at 18:28
  • 1
    @FaustasButkus again, do some research on the items that were mentioned. Particularly "*forward declarations*" – Remy Lebeau Mar 03 '18 at 18:31
  • Possible duplicate of [error: expected class-name before ‘{’ token](https://stackoverflow.com/questions/5319906/error-expected-class-name-before-token) – 1201ProgramAlarm Mar 03 '18 at 20:38

1 Answers1

2

To break the circular references, you should use a forward reference. Since you are using a raw pointer, that's all that is required:

#pragma once

class BoardField;

class Game {
private:
    //members
    BoardField* m_board_fields;
    ...

    //methods
    ...
public:
    ...
};

Of course, in Modern C++ you should be avoiding raw pointers. For a case like a privately owned heap allocation, unique_ptr is the best option in most cases:

#pragma once

#include <memory>

class BoardField;

class Game {
private:
    //members
    std::unique_ptr<BoardField> m_board_fields;
    ...

    //methods
    ...
public:
    ...
};

You should read this blog post

Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81