i thought this was correct, but i get an error saying: main.cpp:14:12: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]
But by assigning variable in the constructor as ints, not array works?
All the examplse i find, are just init and defin array, not in a class. But if you cannot define a member in the class, then how to you define it in the constructor?
You need to read the error more carefully.
It says it is possible, but only using the new standard C++11 (also called c++0x).
You need to compile using the "std" flag:
g++ --ansi -Wall -Wextra -std=c++0x -o test main.cpp
As far as I recall, indeed you used to have to initialise arrays using a for loop.
If you're going to use C++11 anyway - consider using std::array instead of the old style arrays, they provide more protection against buffer overflows.
class test1
{
private:
int pos[2] { 0, 0 } ;
int pos2[3] = { 1, 2, 3 } ;
// http://www.stroustrup.com/C++11FAQ.html#member-init
};
class test2
{
explicit test2( int a = 0, int b = 0 ) : pos{ a, b } {}
// http://www.stroustrup.com/C++11FAQ.html#uniform-initprivate:
int pos[2] ;
int pos2[3] ;
};
class test3
{
explicit test3( int a = 0, int b = 0 ) : pos{ a, b }, pos2{ a+1, b+1, a+b } {}
private:
int pos[2] ;
int pos2[3] ;
};
// etc...
@JLBorges Thanks very much for that, I was unaware that initializer lists could be used in this way - although the name actually kind of gives it away, I only thought of it in the context of the uniformity.
@metulburr Yes that is still C++11 code, I think in C++98 you are stuck with the for-loop solution.
Kind of a noob question but: Does it matter which you compile any code as c++11, or c++98, will it run in the end on other computers? I still dont quite understand the the process from code to open source to others being able to compile the programs also.
C++11 is standard now, the 11 stands for 2011, when it became the standard.
Compiling C++ code could be the most easily explained by saying that the compiler actually translates your C++ code into machine code, which is code which the CPU understands and runs.
Once "translated", this code will run on any processor supporting the same machine code.
This is why you'll find different downloads for the same programs for different processor architectures (a linux distribution for instance). These processors support different machine code languages (called instruction sets), so the C++ code needs to be translated to each of those different languages.
It's kind of like making a website which you want to be understood by many languages. It's not good enough to translate it to one language, because still not everyone will understand it.