You are not populating your Game
array correctly. You are trying to call the Player()
constructor as if it were a regular class method (which it is not), and worse you are calling it via an uninitialized Player*
pointer.
You need to use the new
operator instead, eg:
class Game
{
private:
int maxPlayers;
Player** playersArray;
public:
Game(int aMaxPlayers);
~Game();
}
Game::Game(int aMaxPlayers)
{
maxPlayers = aMaxPlayers;
playersArray = new Player*[maxPlayers];
for(int i = 0; i < maxPlayers; ++i)
playersArray[i] = new Player; // <-- here
}
Game::~Game()
{
for(int i = 0; i < maxPlayers; ++i)
delete playersArray[i];
delete[] playersArray;
}
A safer option is to use std::unique_ptr
instead of raw pointers:
#include <memory>
class Game
{
private:
int maxPlayers;
std::unique_ptr<std::unique_ptr<Player>[]> playersArray;
public:
Game(int aMaxPlayers);
}
Game::Game(int aMaxPlayers)
{
maxPlayers = aMaxPlayers;
playersArray = std::make_unique<std::unique_ptr<Player>[]>(maxPlayers);
for(int i = 0; i < maxPlayers; ++i)
playersArray[i] = std::make_unique<Player>();
}
That being said, there is no need to use an array of Player*
pointers when an array of Player
objects will suffice instead:
class Game
{
private:
int maxPlayers;
Player* playersArray;
public:
Game(int aMaxPlayers);
~Game();
}
Game::Game(int aMaxPlayers)
{
maxPlayers = aMaxPlayers;
playersArray = new Player[maxPlayers];
}
Game::~Game()
{
delete[] playersArray;
}
Or:
#include <memory>
class Game
{
private:
int maxPlayers;
std::unique_ptr<Player[]> playersArray;
public:
Game(int aMaxPlayers);
}
Game::Game(int aMaxPlayers)
{
maxPlayers = aMaxPlayers;
playersArray = std::make_unique<Player[]>(maxPlayers);
}
Which you can then simplify further by using std::vector
instead:
#include <vector>
class Game
{
private:
std::vector<Player> playersArray;
public:
Game(int maxPlayers);
}
Game::Game(int maxPlayers)
: playersArray(maxPlayers)
{
}