5

In Stroustrup's book, "Programming: Principles and Practices of Programming Using C++ (Second Edition)", the author creates a struct as follows:

const int not_a_reading = –7777; struct Day { vector<double> hour {vector<double>(24,not_a_reading)}; }; // As the author says: "That is, a Day has 24 hours, // each initialized to not_a_reading." 

I know vector<double> hour{24, not_a_reading} won't do because it initializes a vector of two elements, 24 and -7777, which isn't the desired object.

But is there any reason why the author's initialization technique is superior to just doing:

vector<double> hour(24, not_a_reading) 

(?)

1 Answer 1

5

In the code above, the following is a class (struct) non static data member hour:

vector<double> hour {vector<double>(24,not_a_reading)}; 

It has a default member initializer: {vector<double>(24,not_a_reading)}

But is there any reason why the author's initialization technique is superior to just doing:

vector<double> hour(24, not_a_reading) 

Yes, you would not be able to write the initializer of a class member that way. You need the curly braces in the class (struct) definition to make it an initializer or you could use the syntax: vector<double> hour = vector<double>(24,not_a_reading); which would mean the same thing.

#include <vector> using namespace std; int main() { const int not_a_reading = -7777; struct Day { vector<double> hour{vector<double>(24,not_a_reading)}; // create a vector of doubles object with the constructor and then initialize hour with 24 doubles vector<double> hour2 = vector<double>(24,not_a_reading); // same as above }; //struct Day2 { // vector<double> hour(24,not_a_reading); // syntax error //}; struct Day3 { vector<double> hour(int,int); // function declaration! }; vector<double> other_hour(24,not_a_reading); // ok here vector<double> other_hour2(); // function declaration, most vexing parse! vector<double> another_hour{vector<double>(24,not_a_reading)}; // also ok here return 0; } 

A possible reason that vector<double> hour(24,not_a_reading); is not allowed to create an hour object is because under certain circumstances it could be confused with a function declaration. The so called most vexing parse.

Sign up to request clarification or add additional context in comments.

1 Comment

More precisely, "you would not be able to write the initializer of a class member that way". That syntax is still perfectly valid for initialization of local and global variables. (And no it isn't a function declaration -- although the potential for confusion with one is why class member initializers require a brace or equals)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.