I have three base Classes {Player,Weapon,Game} and one inherited Class Warrior from Player. The code I added may not be minimal but I added anything that can be relevant. Since I didn't know where to look.
This is my test for simple debugging, I add Players into vectorPlayers which is definded in game.h
int main() {
Weapon w1("hello",STRENGTH,3);
Game game(3);
game.addWarrior("s22","we",STRENGTH,3,55);
//4
game.addWarrior("s22","we",STRENGTH,3,55);
return 0;
}
When I reach the the 4th line, vectorPlayers[0] includes the correct inputs. But when I enter to game.cpp and call the function addPlayer in addWarrior,suddenly players_name for example switches to error: Cannot access memory at address 0x1
//inside game.cpp
GameStatus Game::addPlayer(const string playerName, const string weaponName,
Target target,int hit_strength)
{
Weapon newWeapon(weaponName,target,hit_strength);
Warrior newWarrior(playerName,newWeapon,false);
if(ifNameAlreadyExists(playerName)) {
addRegPlayer(static_cast<Player*>(&newWarrior));
}
return SUCCESS;
}
GameStatus Game::addRegPlayer(Player* player)
{
playersVector.push_back(player);
}
//base classes
class Game {
private:
int maxPlayer;
vector<Player*> playersVector;
}
class Player {
string player_name;
int level;
int strength;
Weapon player_weapon;
protected:
int place;
int life;
public:
Player(const string &name, const Weapon &weapon);
virtual ~Player();
}
//inherited class
class Warrior : public Player {
private:
bool rider;
public:
Warrior ();
Warrior (string const& name, Weapon const& weapon, bool rider);
~ Warrior () override = default;
Warrior &operator=(const Warrior &warrior) ;
Warrior ( const Warrior &warrior) = default;
void makeStep() override;
};
//Constructor of Warrior
Warrior::Warrior(string const& name, Weapon const& weapon, bool rider) :
Player(name,weapon),rider(rider){
if (weapon.getTarget() == LEVEL){
throw IllegalWeapon();
}
}
//constructor of player
Player::Player(const string& name, const Weapon& weapon) :
level(1),life(1),strength(1),player_weapon(weapon),player_name(name),place(0){
}