How to initialize a vector of classes in a constructor?

If I have a class Player and I want a vector of Player inside a class Team, how can I initialize it in the constructor?

--------------------------------------------------
In player.h:
--------------------------------------------------

class Player
{
public:
Player ();
Player (const Player& to_copy);
Player (std::string name, int age, int goals);

//getters, setters, etc.

private:
std::string _name;
int _age;
int _goals;
}

--------------------------------
In team.h
--------------------------------
class Team
{
public:
Team ();
Team (const Team& to_copy);
Team (int wins, std::vector <Player> playVec);

//getters, setters, etc.

private:
int _wins;
std::vector <Player> _playVec;
}

------------------------------
In team.cpp
------------------------------

Team::Team():
_wins(0),
_playVec( ??????????? )
{
}
Last edited on
anyway you want as long as it follows vector constructor syntax:
http://www.cplusplus.com/reference/vector/vector/vector/
As it's the default constructor you're showing with the question marks, the answer is there's (probably) nothing for you to do. As with the std:::string name member,. the std::vector member's constructor will handle default initialization for you.

1
2
3
4
Team::Team():
_wins(0) // you only have to worry about the int
{
}


I say probably as this assumes you will add the players to _playVec with push_back (or equivalent code.) If you want to initialize _playVec with a number of empty players then use, e.g.

1
2
3
4
5
Team::Team():
_wins(0),
_playVec(50)
{
}


But I'm not sure this makes as much sense as the previous approach.

While I'm here, it's better to pass vectors to functions by const ref, similar to the way you are passing the Team to_copy parameter to the copy constructor. (I assume you can work out how to implement the other versions of your constructor?)

And doesn't the team need to be named, too?

Andy
Last edited on
Thank you both for the attention.

Andy, I had tried to do the constructor as you hint me but I think that an "out_of_range" error that I had was given by that. I thought it was empty so doing the push_back on it was the problem.

Now I've understand that the error was another, so thank you! It works as you hinted!
Topic archived. No new replies allowed.