Question

void Player::move(Board &board, Solver &solver){
   Position* best = solver.find_best_move(&board);
   cout<<"Score: "<<best->get_score()<<endl;
   cout<<"Board: ";
   best->get_board()->print_board();
   board = *(best->get_board());
   Board * b(best->get_board());
   cout<<"TEST: ";
   b->print_board();
   board = *b;
  }

I'm trying to make the actual board reference equal to the new board after calling the function. Board is an abstract class and get_board() is returning a pointer to a Board but it is actually a subclass of board which has an extra attribute. However,after the move function is called, the board is the same board as it was before the call to move. Is it possible to assign a subclass to a pointer to an abstract super class, while modifying the actual value? The issue of slicing seems to be occurring.

Was it helpful?

Solution

I would use a Board* pointer instead of a Board& reference, especially since a subclass is involved:

void Player::move(Board **board, Solver &solver)
{ 
   Position *best = solver.find_best_move(*board); 
   cout << "Score: " << best->get_score() << endl; 
   *board = best->get_board(); 
   cout << "Board: "; 
   (*board)->print_board(); 
} 

Player p;
Solver solver;
Board *b = ...;
p.move(&b, solver);

Or:

void Player::move(Board* &board, Solver &solver)
{ 
   Position *best = solver.find_best_move(board); 
   cout << "Score: " << best->get_score() << endl; 
   board = best->get_board(); 
   cout << "Board: "; 
   board->print_board(); 
} 

Player p;
Solver solver;
Board *b = ...;
p.move(b, solver);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top