Home > Net >  how to initializes a collection (list) by copying the parameters from a constructor?
how to initializes a collection (list) by copying the parameters from a constructor?

Time:10-12

I've a class PokemonCollection which has a private list which accepts a pair.

Now what I've to do is, when I make an object"collection" of that class PokemonCollection in main() function, I pass some pairs to the constructor, and in the constructor I've to initialize the private list of the class.

PokemonCollection collection({pair<string, size_t>("Pikachu", 25), 
pair<string, size_t> ("Raticate", 20), pair<string, size_t>("Raticate", 20), 
pair<string, size_t>("Bulbasaur", 1), pair<string, size_t>("Pikachu", 25), 
pair<string, size_t>("Diglett", 50)});

this confuses me alot, can someone kindly help me as I'm a beginner, also I've to print that private list too.

collection.print();

where print is public function of my class.

class definition:

class PokemonCollection{
    public: 
        void print();
    private: 
        list<pair<string, size_t>> pokemons_;
};

where "size_t" is an identifier for the pokemon name. I have this hint in my assignment for the constructor:

  /* constructor
   * initializes the collection to by copying the parameter
   */
PokemonCollection(const std::list<std::pair<std::string, size_t>>& pokemons){}

enter image description here

CodePudding user response:

how to initializes a collection (list) by copying the parameters from a constructor?

Just like you would initialize any other data member in the member initializer list:

class PokemonCollection{
    public: 
        void print();
        PokemonCollection(const std::list<std::pair<std::string,
//---------------------------------------------------VVVVVVVVVVVVVVV--->use member initializer list
                                size_t>>& pokemons): myList(pokemons)
                                {

                                }
    private: 
        list<pair<string, size_t>> myList;
};

Demo

Note that in your given example, you had not given any name to the list data member, so in my example I've named it myList. Then myList is initialized with the function parameter named pokemons using the member initializer list.

  • Related