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.

5
  • 1
    possible duplicate of How can i use member initialization list to initialize it? Commented Dec 30, 2011 at 17:50
  • +1 for trying to use the initializer list instead of assigning the values inside the body of the constructor. Commented Dec 30, 2011 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) Commented Dec 30, 2011 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)[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 ;-) Commented Dec 31, 2011 at 8:30
  • @Andre : Default-initialized, not necessarily default-constructed -- in fact for POD types, there will be no initialization at all. Commented Jan 4, 2012 at 19:33

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
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 :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.