0

I have a struct that only has double member variables, e.g.

struct foo { double a, b, c; };

Another class has a std::vector<foo> v member that calls the std::vector<foo>::vector(size_t) constructor in the initializer list.

What I'd like to do is write a default constructor for foo so that all the doubles in it are initialized to zero, without having to write

foo(): a(0), b(0), c(0) { }

I keep needing to add more variables to foo, but it doesn't make sense to have them be elements of a container like std::array<double>, because they all serve distinct purposes.

SU3
  • 5,064
  • 3
  • 35
  • 66
  • for POD you can use `memset()` – Slava Feb 02 '17 at 19:34
  • 1
    @Dan, maybe in general context, but I was trying to avoid writing a default-initialized-to-zero wrapper around double. – SU3 Feb 02 '17 at 19:39
  • 2
    @Slava - formally, using `memset` here isn't portable; there's no requirement that all-bits-zero represents a floating-point value of 0.0. – Pete Becker Feb 02 '17 at 20:28
  • You know they get initialized to 0 in the vector, right? If yes, then the vector is a red herring. If no, then probably there is no problem to solve. – juanchopanza Feb 02 '17 at 20:59

1 Answers1

7

Since you've tagged this as C++14, you can initialize member variables like this without having to initialize them in a constructor:

struct foo {
    double a = 0.0;
    double b = 0.0;
    double c = 0.0;
};
DeiDei
  • 10,205
  • 6
  • 55
  • 80