Suppose I have a structure (or a class that I use just for storing) filled with doubless. I make a constructor to assign to those doubless:
struct Point {
double time;
double x;
double y;
Point(double a_time, double a_x, double a_y)
: time(a_time), x(a_x), y(a_y) {}
}
It seems redundant to declare members in the class if they are already declared in the constructor.
Is there a way to reduce these redundancy so that members that are used in the constructor are automatically public members of the class? also might be useful for other member functions.
this example is similar to the one on page 348 of Programming: Principles and Practice Using C++. So this is contemporary established style of coding.
Furthermore, I’m looking for a modern C++ style solution, meaning without pre-processor.
Update (1)
this struct needs to be used in the following way:
vector<Point> points
points.push_back(t0,x0,y0)
The way you have it is perfectly fine. However, if you want to just give default values, in C++11 you can initialize your members directly and you don’t need a constructor:
Also, it looks like this struct is just a bag of data, if that is the case you can also use aggregate initialization which works without C++11:
Example 1
Example 2
After update
You can use
push_backlike this with a flat data type: