C++ constructor initialization list

How to initialize the list in C++?

Insert picture description here
Look at a simple code:

class Test
{
    
    
public:
	Test(int a)
	{
    
    
		ma = a;
	}
private:
	const int ma;
};

Operation result: I
Insert picture description here
can see that the program is running wrong, what is the reason?
Insert picture description here
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;
};

Insert picture description here

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?
Insert picture description here
Look at the result:
Insert picture description here
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?
Insert picture description here
Insert picture description here
Only mb = 10, there is ma = 10;
Insert picture description here
is it a bit awkward?

Next we look at the difference between the two pieces of code:
Insert picture description here
Insert picture description here
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
Insert picture description here
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/102965254