I have very technical question, I was working with C, and now I’m studying C++,
if I have for example this class
class Team {
private:
list<Player> listOfPlayers;
public:
void addPlayer(string firstName, string lastName, int id) {
Player newPlayer(string firstName, string lastName, int id);
listOfPlayers.push_back(Player(string firstName, string lastName, int id));
}
};
this is a declaration of the Player:
class Player{
private:
string strLastName;
string strFirstName;
int nID;
public:
Player(string firstName, string lastName, int id);
};
and this is my constructor of Player:
Player::Player(string firstName, string lastName, int id){
nId = id;
string strFirstName = firstName;
string strLastName = lastName;
}
so my question is when I call function addPlayer what exactly is going on with program,
in my constructor of Account do I need to allocate new memory for new Player(cause in C I always use malloc) for strFirstName and strLastName, or constructor of string of Account and STL do it without me, thanks in advance (if you don’t want to answer my question please at least give me some link with information) thanks in advance
Here’s a “correct” implementation of what you have now:
The
push_back()function of list allocates a new node that holds thePlayerinstance and pointers to other nodes, so you have sort of a “chain” ofPlayerinstances.For your question about
Account, if you have this:Then you don’t need to worry about allocating/freeing memory for the character arrays, for
std::stringwill handle that for you.