1

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

user491880
  • 4,709
  • 4
  • 28
  • 49
  • Does this answer your question? [How to initialize std::vector from C-style array?](https://stackoverflow.com/questions/2434196/how-to-initialize-stdvector-from-c-style-array). An analogous pair of constructors are used in that question. – Brian61354270 Nov 17 '21 at 23:18
  • 6
    You're looking for [delegating constructors](https://learn.microsoft.com/en-us/cpp/cpp/delegating-constructors?view=msvc-170), but the *unpack the bytes into vector* stage will have to be handled in a helper function because the delegation is done in the member initializer list, not the function body. – user4581301 Nov 17 '21 at 23:22
  • Second link in the duplicates list will only apply if `item` is an alias for `char`. Based on the question's wording I expect `buf` points to a blob that needs to be deserialized into `item` instances. if that blob came out of a file or other stream, you might also want a `std::istream` constructor overload so you can simply pass the stream in rather than read the stream into a byte array and invoke on the byte array. – user4581301 Nov 17 '21 at 23:34

1 Answers1

2

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))
{}
Walter
  • 44,150
  • 20
  • 113
  • 196