regarding constructor intializer list

why it is said that ..all the data members of a class must be initialized using intializer list rather than intializing them in the constructor.what are performance reasons

//without intializer list
class MyClass {
Type variable;
public:
MyClass(Type a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators
variable = a;
}
};


// With Initializer List
class MyClass {
Type variable;
public:
MyClass1(Type a):variable(a) { // Assume that Type is an already
// declared class and it has appropriate
// constructors and operators

// assume some execution statements are there
}
};

please explain me the how performance changes between the two
Last edited on
The first case calls Type's default constructor to initialize variable, then calls Type's copy assignment operator to destroy the value you just created and replace it with a copy of a.

The second case calls Type's copy constructor
Is there any advantage or disadvantage to doing this instead?

1
2
3
4
5
6
7
8
9
10
11
12
 
class MyClass
{
Type variable;
public:
MyClass(Type a);
};

MyClass::MyClass(Type a)
{
variable = a;
}
Last edited on
Hi Cubbi,

let me take one sample code and the code i mentioned above i modified a little bit please go through. :)

int main()
{
int a=10;
Myclass Hello(a);
Myclass1 Hello1(a);
}

so for the first call ( Myclass Hello(a);)
default constructor will be called of Type then Type's copy constructor and then destructor as 'a' scope is gone

for the second object (Myclass1 Hello1(a);)

firstly the before the body of constructor begins constructor intializor list gets invoked and hence copy construtor will be called first to copy the value
as some statements are there in the constructor then also now we get into the body of constructor hence now constructor of type gets called then followed by destructor

am i correct? if so how we differentiate by performance
These two lines

1
2
MyClass::MyClass(Type a)
{


construct every member of MyClass, whether you like it or not.

The following line
variable = a; throws away what you just constructed and replaces the contents of the member variable.

Aside from the fact that it's not how C++ constructors are normally written, doing something, destroying it, and doing it again is clearly more work than doing it just once, as in MyClass::MyClass(Type a) : variable(a) {}
Even with compiler optimizations, there are cases where the compiler is not allowed to make the fix for you because it would alter the observable behavior.
Topic archived. No new replies allowed.