In C ++, unlike C # and Java, it was not allowed to initialize member variables in the place of the declaration. This was until in August 2011 the C ++ 11 standard was approved, adding this functionality to the standard behavior of the language.
[Here] you have the description of this functionality on the Bjarne Stroustrup (In English), receives the technical name of Initialization of members in class (" In-class member initializers ").
The gcc compiler.
Initialization of members in class is supported in gcc from the version 4.7 1 . To use the C ++ 11 features, you must activate the C ++ 11 mode of the compiler by adding the -std=c++11
parameter to the compilation order, as indicated by the alarm you get when compiling:
warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
unsigned int total=base+dietes;
So you should stop having that alarm if you compile in this way:
g++ base_dades.cc -o base_dades.e -std=c++11
Surely you have a gcc version equal to or higher than 4.7, so the code compiles despite being the wrong code in C ++ standards prior to C ++ 11. As the compile parameter -std=c++11
is not added by default, it shows an alarm (instead of an error) for being able to compile the code despite the absence of the appropriate compilation option.
Initialization of members in class operation
I have the feeling (correct me if I'm wrong) that you expected the output of your code to be:
100
2
102
But this would not happen as the unsigned int total=base+dietes;
instruction is executed at the time of the instance construction of salari
, that is: at the same time as the% instruction salari a;
is executed.
Since members base
and dietes
have no initial value, their value is indeterminate 2 but not infrequently is a value different from 0. So the value 4196768
that you have obtained is the result of adding two random memory values at the time of construct a
.
For the total
to be automatically updated when assigning base
and dietes
you should use assignment functions:
struct salari{
unsigned int base = 0;
unsigned int dietes = 0;
unsigned int total = 0;
void assigna_base(unsigned int valor){
base = valor;
total = base + dietes;
}
void assigna_dietes(unsigned int valor){
dietes = valor;
total = base + dietes;
}
};
So, your main
with these functions:
int main(){
salari a;
a.assigna_base(100);
a.assigna_dietes(2);
std::cout << a.base << '\n'
<< a.dietes << '\n'
<< a.total << '\n';
return 0;
}
I would give this exit
100
2
102
Notice that I have initialized 0
all members of salari
with Initialization of members in class.
Molta sort Pol, fins an altra:)
1 [Here] you can see the features added to C ++ and in which version of gcc were implemented.
2 Any uninitialized data contains as a value that which contains the memory assigned to it, which could be any value.