0

How do I initialize private string variables name and age in my constructor to "John", and 30?

class Name_pairs
{
public:
    Name_pairs();
    Name_pairs(string name_cons, double age_cons);
    vector <string> read_names() {return name;};
    vector <double> read_ages() {return age;};
    void print();
    void sort();

private:
    vector <string> name;
    vector <double> age;
};

Name_pairs::Name_pairs()
    : name(), age()
{}

The usual :private_variable(default value) doesn't work. Sorry if noobish question, first time encountering classes.

3
  • you don't need vector for name and age if Name_pairs serve for one person only. Commented Apr 10, 2015 at 11:22
  • Besides you not needing vectors, just abut any book or tutorial should have told you how to initialize member variables in a constructor. Commented Apr 10, 2015 at 11:25
  • @Joachim It did, but not if vectors are member variables. Commented Apr 10, 2015 at 11:59

2 Answers 2

1

you try to initialize the vector name with a string. These are 2 different data types. As billz already suggested, you won't need a vector of strings for a name_pair (or your class naming is misleading for billz and for me). If you would declare name as a string, you could use the constructor's initialization list again.

...
private:
    string name;
    double age;
};

Name_pairs::Name_pairs(string name_cons, double age_cons)
    : name(name_cons), age(age_cons)
...

When you have just named your class ambigous and you really need a vector of strings in your class and you only get strings as constructor parameters, you will have to add those strings in the constructors body into your vectors.

Name_pairs::Name_pairs(string name_cons, double age_cons)
{
  name.push_back(name_cons);
  age.push_back(age_cons);
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's part of the task I'm doing. It could be I misunderstood it, but it does say to use strings as variabbles. This code also works, thank you!
1

Like so:

Name_pairs::Name_pairs()
    : name( 1, "John" ), age( 1, 30 )
{}

1 Comment

@Luka This creates a vector of length 1 and initializes all elements to "John" or 30, respectively. This makes more sense if your vector is initialized with many elements, but it also works if it's only one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.