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

devx-admin

Share the Post: