c++constructorconstructor-chaining

C++ delegate constructor with some work done beforehand


I'm trying to do something along the lines of

class A {
    A();
    A(int num);
}

A::A()
{
    int i = /* Something that loads something */
    A(i);
}

A::A(int num)
{
    /* something involving num */   
}

I am aware of delegated constructors in C++ 11, what I am wondering is if it's possible to do something before invoking the delegated constructor.

Also, unrelated, but is this available in an initializer list?


Solution

  • Some alternatives:

    Default argument:

    struct A { 
      explicit A(int i = load_something());
    };
    

    Deferred constructor:

    struct A { 
      explicit A(int i);
      A() : A(load_something()) {}
    };