7

Im trying something like this (which doesnt compile):

struct mystruct {
    somestruct arr[4];
    mystruct(somestruct val) : arr[0](val), arr[1](val), arr[2](val), arr[3](val) {}
};

How is this best done in c++ ?

Note: i might want to set only some of the array elements with this method.

Rookie
  • 4,064
  • 6
  • 54
  • 86
  • 1
    possible duplicate of [How can i use member initialization list to initialize it?](http://stackoverflow.com/questions/5602030/how-can-i-use-member-initialization-list-to-initialize-it) – ildjarn Dec 30 '11 at 17:50
  • +1 for trying to use the initializer list instead of assigning the values inside the body of the constructor. – Andre Dec 30 '11 at 17:56
  • @Andre, is there any performance differences with "assigning the values inside the body of the constructor" ? (i cant test since i dont have the compiler that Mike's example uses) – Rookie Dec 30 '11 at 17:58
  • @Rookie if you don't use the initializer list, the values will be default constructed before being assigned. Therefore, using the initializer list will usually be faster. More important, the intent is clearer (at least to my eyes ;-) if you use the initializer list. Not using an initializer list (if possible) would be premature pessimization (see (C++ Coding Standards)[http://www.informit.com/store/product.aspx?isbn=0132654458] which I would recommend to read if you want to improve your C++ skills). Just keep in mind that there's premature optimization as well ;-) – Andre Dec 31 '11 at 08:30
  • @Andre : _Default-initialized_, not necessarily default-constructed -- in fact for POD types, there will be no initialization at all. – ildjarn Jan 04 '12 at 19:33

1 Answers1

6

In C++11, if you want to set all the elements:

mystruct(somestruct val) : arr{val,val,val,val} {}

In C++03, or C++11 if you only want to set some elements:

mystruct(somestruct val) {
    arr[0] = val;
    arr[1] = val;
    arr[2] = val;
    arr[3] = val;
}
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 1
    Too bad it doesnt work on visual-c++ compiler, im using the latter at the moment, thought there was better way. Btw, does the compiler optimize the latter as fast as the above? – Rookie Dec 30 '11 at 17:56
  • In order to compile, you might need to use the -std=c++11 flag. You should have some kind of preference pane where you can set it. – Mihai Neacsu Mar 05 '14 at 21:09
  • With `-std=c++0x` compiler option all I did was `classname::clasname(): array{num1,num2,num3,num4} { /* all constructor functions or methods or variable assignments go here*/ }`. I initially got confused what `{}` at the end in your solution was but then quicky realized it is the body of the constructor :-) – enthusiasticgeek Dec 29 '14 at 02:09