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.

See also  5 Ways to Improve Customer Experience

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist