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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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;
		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
Thanks for your registration, follow us on our social networks to keep up-to-date