Search code examples
c++constructorinitialization

Two interdependent member functions with no default constructor


I am sure that this question must be answered somewhere, but I cannot formulate the question... My issue is that I have two objects (foo, bar), where bar needs to be initialized using foo instance. How to do it, when both objects are data members of another class (baz)?

I cannot initialize bar in baz constructor body as bar in this time must have been already initialized using default constructor that it is missing.

I cannot initialize bar in baz initializer list as foo has not been constructed in this time. Watch out as compiler does not care!

See the example:

#include <iostream>
#include <memory>

using namespace std;

class foo
{
   public:
      foo() {
         cout << "foo constructor called." << endl;
      }

   private:
};

class bar
{
   public:
      bar(foo inFoo) : mFoo(inFoo) { 
         cout << "bar constructor called." << endl; 
      }

   private:
      foo mFoo;
};

class baz
{
   public:
      baz() : mBar(mFoo) { 
         cout << "baz constructor called." << endl; 
      }  // ERROR: mFoo is not inizilized

   private:
      bar mBar;
      foo mFoo;
      
};

int main()
{
   baz Baz;
}

Only workaround that comes to my mind is using pointers in the baz class. Using of a pointer for bar data member allows me to postpone initialization until baz constructor body.

class baz
{
   public:
      baz() {
         cout << "baz constructor called." << endl;
         mBar = unique_ptr<bar>( new bar(mFoo) );

      }

   private:
      unique_ptr<bar> mBar;
      foo mFoo;

};

But is it possible to solve this problem without pointers?


Solution

  • Since mBar depends upon mFoo, just reorder the declarations:

    private:
        foo mFoo;
        bar mBar;
    

    and initialize mFoo first:

    baz() : mFoo(), mBar(mFoo) { 
      // ...
    }
    

    Here's a demo.