Nicolas Nicolas - 1 year ago 86
C++ Question

Initializer List Perfomance in C++?

I am totally new to programming in c++ and now learning about constructors. In a blog post about constructors which I read before written that using "Initializer list" is better that assigning values inside body in the class constructor when initialzing class variables due to performance reasons. But there are not any explanation reasons behind it. If you can explain it I would be grateful.

Answer Source

Firstly your question in not complete. There are some specific cases indeed. But for simplicity :

class Foo {
    ExampleType var;
    Foo(ExampleType x):var(x) {


Firstly the copy constructor of “ExampleType” class is called to initialize : var(x) then destructor of “ExampleType” is called for “x” since it goes out. But in variable assignment case, firstly constructor called for Example type then assignment operator is called and so the destructor called.