Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
May 4, 2005

Be Careful When Assigning Data Members During Initialization

Be careful how you assign data members during initialization. For example, consider the following code:

class test
{
	public:
		test (int y) : j (y), i(j)
		{
		}
	private:
		int i;
		int j;

};
When compiled, the compiler interprets that as:

test (int y)
{
	i = j;
	j = y;
}
Because the compiler initializes and assigns data members in the order that you declared them, the compiler's generated code gets inserted in the member initialization list in the constructor body before your code.

A safe way around this is to redefine your ctor as follows:


test (int y ) : j(y)
{
	i = j;
}
Using the preceding definition, the compiler generates the following code:

test(int y)
{
	j = y;
	i = j;
}
Saurabh Ramya
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap