>

which is better,Initialisation list or assignment for intialization of data members of a class

For a variable inside a class there are two ways to initialize it.Either initialization list can be used or inside constructor data members can be initialized.

Now out of these two ways using initialization list is efficient.Compiler does not make a separate copy of  data members of a class to be initialized.

Ex- class A{

int x;

};

A::A():x(temp){}

the other one is assignment inside constructor

A::A(){

x=temp;

}

This is inefficient because a separate copy of object is created here and passed to x object’s assignment operator.Then temp gets destructed at ;(x=temp;) .Code runs faster when initialization list is used.

There is exception to this also.Initialization list can create troubles when there are two constructors of class and they are initializing data members of class in different orders.Certainly a debatable topic for efficiency.

Leave a Reply