devxlogo

Mem-initializer Evaluation Order

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.

devx-admin

Share the Post: