Search code examples
c++ctor-initializer

Is it possible to initialize a member variable in the constructor body, instead of the initializer list?


As you might know,

A::A() {
    this->foo = 1;
}

Is the same as:

A::A() : foo(1) {
    this->foo = 1;
}

Which is inefficient because of the double declaration.
The compiler might optimize this, but in my case the class is not a POD.
I must define the member in the constructor body since it can't be compressed into one single line.

Is there any way of doing this?


Solution

  • No, you cannot initialise in the constructor body. It must be done in the mem-initialiser list, or using in-class initialisers (at member declaration). However, nothing prevents you from calling a function (or a lambda) to do the initialisation:

    A::A() : foo([]() { /* ... */ } ())
    {}
    
    // or
    
    A::A() : foo(initFoo())
    {}
    
    Foo A::initFoo() { /* ... */ }