I'm just messing around with some C++ at the moment trying to make a simple tic-tac-toe game and I'm running into a bit of a problem. This is my code:
#include <iostream>
using namespace std;
class Square {
public:
char getState() const;
void setState(char);
Square();
~Square();
private:
char * pState;
};
class Board {
public:
Board();
~Board();
void printBoard() const;
Square getSquare(short x, short y) const;
private:
Square board[3][3];
};
int main() {
Board board;
board.getSquare(1,2).setState('1');
board.printBoard();
return 0;
}
Square::Square() {
pState = new char;
*pState = ' ';
}
Square::~Square() {
delete pState;
}
char Square::getState() const {
return *pState;
}
void Square::setState(char set) {
*pState = set;
}
Board::~Board() {
}
Board::Board() {
}
void Board::printBoard() const {
for (int x = 0; x < 3; x++) {
cout << "|";
for (int y = 0; y < 3; y++) {
cout << board[x][y].getState();
}
cout << "|" << endl;
}
}
Square Board::getSquare(short x, short y) const {
return board[x][y];
}
Forgive me if there are blatantly obvious problems with it or it's stupidly written, this is my first program in C++ :p However, the problem is that when I try and set the square 1,2 to the char '1', it doesn't print out as a 1, it prints out as some strange character I didn't recognise.
Can anyone tell me why? :)
Thanks in advance.
The Board::getSquare method is returning a copy of the Square object. The pState variable of the copied Square object points to the same character as the original Square object. When the copied Square object is destroyed, it deletes the char object pointed to by the pState variable. This invalidates the char object in the Square object in the Board. When you go to print, you are printing an invalid char object.
As others has stated, the pState variable should probably be a char rather than a char*. This will move you a step forward in resolving your issues. You still need to deal with returning a reference to the Square object rather than a copy of the Square object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With