kirill_igum
kirill_igum

Reputation: 3983

create members automatically if they are used in construction

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)

Upvotes: 0

Views: 59

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

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:

struct Point {
  double time = 0.0;
  double x = 0.0;
  double y = 0.0;
};

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

struct Point {
  double time;
  double x;
  double y;
} p = {0.0, 0.0, 0.0};

Example 2

struct Point {
  double time;
  double x;
  double y;
};

Point p1 = {0.0, 0.0, 0.0};

After update

You can use push_back like this with a flat data type:

v.push_back({t0, x0, y0});

Upvotes: 3

Related Questions