Search code examples
c++constructordelegating-constructor

C++ constructor delegation, but how to (sort of) invert?


I understand that in C++11 constructor delegation can looks like this:

class Foo
{
 public:
  Foo()
   {
     // Some code to be ran first
   }
  Foo(std::string bar): Foo() // Runs the code to be ran first
   {
    // Some code to be ran second, presumably using bar
   }
};

I want to know how to invert this situation, in a way. Namely, in the case the Foo() constructor is called, I want to run some code to figure out a value for a std::string that would then be used by Foo(std::string bar) to finish initialization. So Foo() runs both its own code and the code in Foo(std::string bar), while the the latter runs only its own code, something like

class Foo
{
 public:
  Foo()
   {
     std::string bar_figured_out;
     // Figures out the value for bar_figured_out

     Foo(bar_figured_out); // I know this wouldn't work, just an example of what I'm trying to do.
   }
  Foo(std::string bar):
   {
    // Some code to finish class initialization, using bar
   }
};

Is there any way to accomplish this using constructor delegation?


Solution

  • You have two options:

    • Move the code from Foo(std::string bar) to a member function, and call it from both Foo() and Foo(std::string bar).

    • Move the code that determines the value of bar_figured_out to a member function, and then have Foo() call that function when delegating to Foo(std::string bar):

      Foo() : Foo(compute_bar()) {}