devxlogo

Be Careful When Assigning Data Members During Initialization

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;}
devxblackblue

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