Login | Register   
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
Home » Tip Bank » C++
Language: C++
Expertise: All
May 6, 1998

Mem-initializer Evaluation Order

When initializing objects data members by a mem-initializer list, the compiler transforms the list into the order of the declaration of the data members in that class:
 
	class A {
		int &a;
		int b;
		public:
		A(int aa, int bb) : b(bb), a(aa) {} //1
			
	};
Since a is declared in A before b, the constructor in //1 above is automatically transformed by the compiler into:
 
	 A(int aa, int bb) : a(aa), b(bb) {}
This may cause a nasty bug like this:
 
	A(int bb) : b(bb), a(b) {} //transformed by the compiler into:
	A(int bb) : a(b), b(bb) {} //oops: 'a' has undefined value now
A clever compiler may warn about that, but it's best to adhere to the order declaration of the class data members in a mem-init list.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap