I'm trying to make a very simple programming language that lets someone play a battleship game for a school project in Flex/Bison. In order to store my variables, I have a map called symbol_table that takes a string for the key and has a Variable* for its value. The inheritance tree is as follows:
class Expression {
public:
Type type;
virtual ~Expression(){} //to make it polymorphic
};
class Variable : virtual public Expression {
public:
char* name;
Variable* next;
virtual ~Variable(){ //also for polymorphism
delete name;
delete next;
}
};
class Player : virtual public Variable{
public:
std::string playerName;
std::vector<GameBoat> playerBoats;
Grid opponentGrid;
Grid playerGrid;
Player(std::string playerName){
this->playerName = playerName;
}
bool addBoat(std::string boatName, char scolumn, int srow, bool vertical){
//make new boat here and then push it back to the vector
GameBoat newBoat(boatName); //this works --> makes a valid boat
if(newBoat.assignedValue){
playerBoats.push_back(newBoat); //SEGMENTATION FAULT HAPPENS HERE
return true;
}else{
return false;
}
}
};
class Computer : public Player{
public:
Computer(std::string playerName) : Player(playerName){}
};
Everything works great when I put Player pointers and Computer pointers into the map, but when I try to retrieve those values again using a dynamic_cast to downcast the base Variable* to a Player* or a Computer*, all of the attributes of the casted Player* or Computer* are NULL and thus give me a "Segmentation Fault: 11" error. I am, however, able to access the class methods that are within the Player and Computer classes.
Variable* var = get_symbol($1);
if (var == NULL) {
sprintf(errormsg, "%s not found.\n", $1);
yyerror(errormsg);
}else if(var->type == PlayerType){
Player* myPlayer = dynamic_cast<Player*>(var); //Cast var to Player*
myPlayer->addBoat("aircraftcarrier", 'a', 1, true); //Enters this function
}else if(var->type == ComputerType){
Computer* myComputer = dynamic_cast<Computer*>(var); //Cast var to Computer*
myComputer->addBoat("aircraftcarrier", 'a', 1, true); //Enters this function
}
How can I be accessing the derived class's methods but not have access to the derived class's attributes? I'm using polymorphism and dynamic_cast doesn't return a NULL value (otherwise the program would never enter the functions and give a Segmentation Fault right away).