How to initialize STL containers in a constructor's initializationlist?

L

luckboyrocky

For the Student class that follows, I'd like to initialize the _scores
vector also as part of the constructor. How do I modify the
initialization list for this? Basically, I don't want to add this code
to the constructor body, and would like to keep the constructor body
empty, and do all initialization as part of the initialization list.

The initialization I had in mind was something like this:
vector<unsigned int> _scores(5, 0); // Vector of five zeroes.

Any ideas?
Thanks,
Xael Banes


class Student {
private:
string _name;
unsigned int _roll_number;
vector<unsigned int> _scores;

public:
Student(string name, int roll_number) :
_name(name), _roll_number(roll_number) { }
};
class Student {
private:
string _name;
unsigned int _roll_number;
vector<unsigned int> _scores;

public:
Student(string name, int roll_number) :
_name(name), _roll_number(roll_number) { }
};
 
N

Neelesh

For the Student class that follows, I'd like to initialize the _scores
vector also as part of the constructor. How do I modify the
initialization list for this? Basically, I don't want to add this code
to the constructor body, and would like to keep the constructor body
empty, and do all initialization as part of the initialization list.

The initialization I had in mind was something like this:
vector<unsigned int> _scores(5, 0);   // Vector of five zeroes.

Any ideas?

Add exactly the same constructor call in the initialization list:
class Student {
  private:
  string _name;
  unsigned int _roll_number;
  vector<unsigned int> _scores;

  public:
  Student(string name, int roll_number) :
    _name(name), _roll_number(roll_number) { }};
  Student(string name, int roll_number) :
    _name(name), _roll_number(roll_number), _scores(5,0) { }};
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top