Home > Blockchain >  Calling another constructor C
Calling another constructor C

Time:11-18

I have something like this:

Foo::Foo(vector<item> items) {
    // do stuff
}

I'd like to call this constructor from another constructor:

Foo::Foo(char* buf, size_t num) {
    // unpack the bytes into vector
    Foo::Foo(items);
}

Is this possible in C 17 ? I know that you can call another constructor using an initialize list, but this seems trickier

CodePudding user response:

Simply call a delegating constructor. Use a helper function to construct the vector<item>.

namespace {
vector<item> helper(char*buff, size_t num)
{
    /* your implementation for re-packaging the data here */
}
}

Foo::Foo(char*buff, size_t num)
  : Foo(helper(buff,num))
{}
  • Related