Dynamically Bind dang you! :)
I am working on a chess program. I have a base class called Piece and then other classes like Pawn, Rook, etc... Problem is that I can't get them to do dynamic binding. Here's the code that needs to do the dynamic binding:
Code:
vector<location> Board::possibleMoves(location loc)
{
Piece* temp = &board[loc.row][loc.col];
vector<location> listLocs;
listLocs = temp->getMoves(board);
return listLocs;
}
in the piece class it looks like:
Code:
virtual vector<location> getMoves(vector<vector<Piece> > board)
{
cout<<"pay attention: "<<endl;
vector<location> temp;
return temp;
}
Finally I want the pawn class to overload this particular function and it looks like:
Code:
vector<location> getMoves(vector<vector<Piece> > board)
{
cout<<"We made it"<<endl;
vector<location> temp;
//A bunch of stuff to figure out possible moves for a pawn
return temp;
}
You can see my debug code. It's still in there. When the function is called, it prints "pay attention" instead of "we made it". Any thoughts on what needs to be changed to make this perform dynamic binding?
Re: Dynamically Bind dang you! :)
I think your problem is due to slicing off the derivedness, but im too tired to give more than a hint. Read about slicing in c++ and you should figure it out.
Re: Dynamically Bind dang you! :)
Quote:
Originally Posted by
black_spot1984
Problem is that I can't get them to do dynamic binding. Here's the code that needs to do the dynamic binding:
That is because pplymorphism requires pointers and references.
A vector<Piece> can only store Piece objects. It cannot store objects derived from Piece. Attempting to store derived objects will cause slicing (the derived part is sliced off, leaving only a Piece object).
The vector should be vector<Piece*>, not vector<Piece>.
Regards,
Paul McKenzie