Reputation: 375
I am getting the following error
game.cpp:19:35: error: ‘Player Game::p1’ is private within this context
19 | Point playerMove = tictactoeGame.p1.makeMove();
| ^~
In file included from game.cpp:1:
game.hpp:12:10: note: declared private here
12 | Player p1;
Followed by 3 errors of the same exact situation with the other variables. I thought I could access these members as they were a part of the Game object.
Here is my class I am referring to
// game.hpp
#ifndef GAME
#define GAME
// Includes
#include "player.hpp"
#include "board.hpp"
class Game
{
private:
Board gameboard;
Player p1;
Player p2;
public:
Game(Board& gb, Player& p1, Player& p2);
bool checkWinner(); // Determine if their is a winner or tie, or if the game is still going.
void announceResults(int winner); // Announce the winner and end the game.
bool checkMoveValidity(const Point& sector); // Check if the players move is a valid move.
};
#endif
//game.cpp
#include "game.hpp"
Game::Game(Board& gb, Player& p1, Player& p2) : gameboard{gb},p1{p1},p2{p2} {}
// Some functions that were implemented
// Main to test out some functions
int main()
{
Board tictactoeBoard;
Player x('x',"Caleb");
Player o('o',"Caleb2");
Game tictactoeGame(tictactoeBoard, x, o);
Point playerMove = tictactoeGame.p1.makeMove(); ///// Error here
while(true)
{
if(tictactoeGame.checkMoveValidity(playerMove))
{
tictactoeGame.gameboard.placePiece(playerMove,tictactoeGame.p1); ///// Error here
break;
}
else
{
std::cout << "Invalid move. Please enter a valid move.";
playerMove = tictactoeGame.p1.makeMove(); ///// Error here
}
}
}
Also, here are the members as defined in player.hpp
and board.hpp
//player.hpp
class Player
{
private:
char symbol;
std::string name;
public:
//////
}
//board.hpp
class Board
{
private:
std::array<std::array<char,3>,3> board;
public:
int rows;
int cols;
}
Although these objects also have private attributes, I thought they would be accessible within the game class.
Do I need to make Game
a friend in both of these classes, or would that break encapsulation?
Upvotes: 0
Views: 171
Reputation: 2515
As the commenters have pointed out, the lines of code causing the error are within the main
function, which, as a standalone function, cannot access private variables of the class. Only methods of the class can access private variables.
Upvotes: 3