Code breaking when trying to set member variable in constructor
I h开发者_开发知识库ave a class like this:
class Player
{
public:
Player(Board * someBoard);
void setSide(char newSide);
protected:
Board * board;
char side;
};
and its implementation is as such:
Player::Player(Board * someBoard)
{
board = someBoard;
side = '0';
}
void Player::setSide(char newSide)
{
side = newSide;
}
Now I have another class inheriting from it:
class HumanPlayer : public Player
{
public:
HumanPlayer(Board * someBoard);
};
And its short implementation is this:
HumanPlayer::HumanPlayer(Board * someBoard) : Player(someBoard)
{
}
Now the problem is the side = '0';
line makes the program freeze (the window turns white in Windows 7, not sure if that means it froze or crashed). Commenting it out make the program run fine (and it's okay to comment it out because the variable isn't used anywhere yet).
What is causing the error and how can I fix it?
EDIT!
After printing out some stuff to an fstream
, all of a sudden the program worked. I tried commenting the printing out. It still worked. I tried deleting the debugging code I added in. It still worked. So now my code is exactly the same as listed above, but it magically works now.
So what do I do now? Ignore the anomaly? Could it have been a compiler mistake?
I suspect the problem isn't what you think it is.
It sounds like a memory corruption issue of some sort, but it's really impossible to tell based on the information provided. I have two suggestions for you:
- Either post the smallest complete program that demonstrates the problem, or
- Try a valgrind-type tool to see if it helps you figure out what's going on.
Or, better yet, start by looking at the state of the program in the debugger (once it's hung.)
Is it possible that you are using two incompatible definitions of your Player class, defined in different header files? If the definitions have different sizes, then the 'size' member might lie outside the memory block allocated for the class instance.
Edit I see that your problem has disappeared. So it was probably a module that didn't get re-compiled after a change in the class definition; but now that you've re-compiled everything, the problem has fixed itself.
精彩评论