How to initialize the list in C++?
Look at a simple code:
class Test
{
public:
Test(int a)
{
ma = a;
}
private:
const int ma;
};
Operation result: I
can see that the program is running wrong, what is the reason?
The reason is that const-modified variables must be initialized.
So how do you initialize const-modified variables in C++?
Look at the following piece of code:
class Test
{
public:
Test(int a):ma(a)
{
//ma = a;
}
private:
const int ma;
};
Of course, in reality, there are more than one variables in many cases. So, what does the execution order in the constructor initialization list have to do with?
Look at a piece of code:
class Test
{
public:
Test(int a)
:ma(mb), mb(a)
{
}
void Show()
{
std::cout << "ma: " << ma << std::endl;
std::cout << "mb: " << mb << std::endl;
}
private:
int ma;
int mb;
};
int main()
{
Test test(10);
test.Show();
return 0;
}
What are the values of ma and mb? ma = mb = 10?
Look at the result:
you can see that ma is an invalid value (cccccccc is used for initialization when opening memory, and cccccccc is an invalid value) mb = 10; it can be seen that mb itself has not yet been assigned to ma Assigned by a;
look at the code below:
class Test
{
public:
Test(int a)
:ma(mb), mb(a)
{
}
void Show()
{
std::cout << "ma: " << ma << std::endl;
std::cout << "mb: " << mb << std::endl;
}
private:
int mb;
int ma;
};
int main()
{
Test test(10);
test.Show();
return 0;
}
What are the values of ma and mb at this time, and are they the same as before?
Only mb = 10, there is ma = 10;
is it a bit awkward?
Next we look at the difference between the two pieces of code:
you can see that the only difference between the codes at both ends is the order of variable declaration.
Therefore, the order of execution in the initialization list of the **C++ constructor is related to the order of declaration of members, not to the order of implementation. **
Look again at the result of swapping the order of realization