c++oopconstructor

Constructor in for loop


I have just started with OO and I have a question about constructors. This would just create the same object "Team a" over and over with a different parameter i, correct?

for (int i = 1; i < n+1; i++) Team a (i); // construct teams

How can I create different "Teams", i.e. Team a, Team b ... Team h if I know how many teams there has to be? Can't the parameter i be the attribute and the name at the same time (Team 1, Team 2, ...)?

This is the constructor I'm using:

public:
    // this will set number to n and points, goals_scored, goals_lost to 0
    Team(int n);

Solution

  • You can use a std::vector:

    std::vector<Team> teams;
    
    for(int i = 0; i < n; ++i)
        teams.emplace_back(i + 1); // makes Team(i + 1) in vector
    

    Note: the std::vector uses zero based indexing so your team #1 is index 0:

    teams[0]; // team #1
    teams[1]; // team #2
    teams[n]; // team #n + 1