-
December 3rd, 2008, 12:13 AM
#1
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?
-
December 3rd, 2008, 01:00 AM
#2
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.
Get Microsoft Visual C++ Express here or CodeBlocks here.
Get STLFilt here to radically improve error messages when using the STL.
Get these two can't live without C++ libraries, BOOST here and Loki here.
Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
Always use [code] code tags [/code] to make code legible and preserve indentation.
Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.
-
December 3rd, 2008, 01:09 AM
#3
Re: Dynamically Bind dang you! :)
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|