Assignment and initialization of class member variables

Source: Internet
Author: User
Tags constructor

C + + stipulates that the initialization action of a member variable of an object occurs before entering the constructor body.

#include <iostream>
#include <string>
using namespace std;

Class STU
{public
:/
	*
	name is initialization, sex and age are assigned */
	STU (string _name,string _sex,int _age): Name ( _name)
	{
		sex=_sex;
		age=_age;
	}
	void Printstu ()
	{
		cout<< "name:" <<name<<endl<< "Gender:" <<sex<<endl< < "Age:" <<age<<endl;
	}
Private:
	string name;
	string sex;
	int age;
};
int main ()
{
	STU s ("Chen", "male", +);
	S.printstu ();
	return 0;
}
In the above program, name is initialized in the initialization list, and sex and age are assigned values in the constructor body.

Name uses a copy construct one step, and sex calls the default constructor initialization before calling the copy operator. Increases the overhead.

For built-in types, such as int age, there is little difference between assignment and initialization.

Therefore, the initialization should be done in the member variable initialization list whenever possible.

initialization Order of member initial value columns

#include <iostream>
#include <string>
using namespace std;
Class STU
{public
:
	STU (int _age): "Money", Age (_age)
	{
	}
	void Printstu ()
	{
		cout<< "Age:" <<age<<endl<< "Money:" <<money<<endl;
	}
Private:
	int age;
	int money;
};
int main ()
{
	STU s (+);
	S.printstu ();
	return 0;
}
A sudden look, as if this initialization list has a problem: first with age to initialize money, and then initialize the age, it is not money using a wrong value to initialize.

In fact, the initialization order of the member initial columns depends on the order in which the member variables are declared.

Private
int age;
int money;

Declares the age, declaring money, so there is no problem with dirty initialization.

However, it is best to keep the initialization list consistent with the order of declarations.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.