How do I initialize an array within a class in c++ without using Initialization Lists (which I think is a c++11 feature)? My compiler (VS2013) does not support c++ 11 to its full extent, sadly.
Asked
Active
Viewed 168 times
-1
-
this thread seems relevant: http://stackoverflow.com/questions/161790/initialize-a-const-array-in-a-class-initializer-in-c – taocp Sep 16 '14 at 01:55
-
You can only initialize non-static data members (inside a class) in C++11. – Sep 16 '14 at 01:55
-
`std::array` is supported by VS2013. – Yakk - Adam Nevraumont Sep 16 '14 at 02:32
-
Do you need to initialize the array differently than zero initialization? – R Sahu Sep 16 '14 at 03:29
1 Answers
1
Visual Studio 2013 supports Initializer lists
, this means you can easily do :
--C++11: default initialization using {}
int n{}; --zero initialization: n is initialized to 0
int *p{}; --initialized to nullptr
double d{}; --initialized to 0.0
char s[12]{}; --all 12 chars are initialized to '\0'
string s{}; --same as: string s;
char *p=new char [5]{};
vector<int> vi {1,2,3,4,5,6};
vector<double> vd {0.5, 1.33, 2.66};
etc
Or other forms which are supported in C++11.
if you are not fond of it you can also use the older methods such as :
You can simply do as follows:
int bar [5] = { 10, 20, 30 };
Which creates an array like this:
---------------------------------
| 10 | 20 | 30 | 0 | 0 |
---------------------------------
You can also have :
int baz [5] = { };
which translates to :
-------------------------------
| 0 | 0 | 0 | 0 | 0 |
-------------------------------
or you might have :
int foo [] = { 16, 2, 77, 40, 12 };
which translates to :
----------------------------------
| 16 | 2 | 77 | 40 | 12 |
----------------------------------
If you are dealing with classes and their objects you can simply call your constructor like this:
Point aPoint[3] = {
Point( 3, 3 ),
Point( 13, 6 ),
Point( 32, 98 )
};
All the former rules apply to this form as well. If you declare an static array, they will be initialized based on their types default (e.g int defaults to 0 and etc)

Hossein
- 24,202
- 35
- 119
- 224