Search code examples
c++oopfriend

C++ friend function


I'm making chess game for my uni and I have to use at least one friend function.

So here is my BoardField class header:

#include "Game.h"

class BoardField {
private:
    ChessPiece m_piece;
    SDL_Rect m_field;

public:
    BoardField();

    friend void Game::init_board_fields();
};

Partial Game class header:

class Game {
private:
    //members
    ...

    //methods
    ...
public:
    void init_board_fields();
    ...
};

And the method:

void Game::init_board_fields()
{
    int field_width = m_window_props.w / 8;
    int field_height = m_window_props.h / 8;
    int field_index = 0;

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            BoardField field;
            // here I get the error that member m_field is inaccessible
            field.m_field = { j * field_width, i * field_height, field_width, field_width };
            m_board_fields[field_index++] = field;
        }
    }
}

So I get this error (look for comment in last code block). Do I poorly understand friend? Does this keyword allow access to private members/methods or does something else?


Solution

  • I simply want to say that a friend method c++ is not part of any class. This being said, your friend method is not part of the class BoardField but it is trying to access its private member(Which is wrong).

    Game class header has to be implemented in Game.cpp not in BoardField class. You are getting the error because you are trying to access a private member of BoardField class through a method declared in Game class.Here I am leaving out the friend concept.

    A proper way to use friend concept in your case would be to make your BoardField Class a Friend of Game Class. This way, Game class will have access to everything in class BoardField. This will eventually work in what your are trying to do.

    You simply have to declare : friend BoardField in your Game class.

    class Game {
    private:
        //members
        ...
    
        //methods
        friend BoardField;
        ...
    public:
        void init_board_fields();
        ...
    };