c++member-initialization

Initializing from a pair in constructur intializer list


I have a function f returning a pair of objects of classes A and B:

auto f() -> std::pair<A,B>;

Furthermore, I have a class C that has A and B as members:

class C {
  public:
    C();
  private:
    A a;
    B b;
};

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

C(): a(f().first), b(f().second) {}

This calls f twice though and it is a quite complicated function. Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.


Solution

  • Improving on the idea from AnkitKumar's answer:

    class C
    {
        A a;
        B b;
        
        C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {}
    
      public:
        C() : C(f()) {}
    };