1. 6
  1. 3

    You can also make Foo a template and provide Bar as the template parameter. This means that Foo and Bar’s headers become independent and you need both only for compilation units that use Foo<Bar>. This allows you to easily test Foo<MockBar> and avoids the double memory allocation for Foo and Bar.

    1. 1

      Another problem is that you don’t get to construct it any particular way. It just pops into being via the default constructor sans arguments, assuming that’s even possible. If it does need arguments, then you can’t even do it this way.

      That’s not true. You just have to add an initializer to your outer class’s constructor:

      Outer::Outer(int param)
      :_bar(true, 8.5, “qux”, param)
      { }

      Another solution to this is the pImpl pattern, where your class is just a shell around an “Impl” class defined inside your .cpp file, and its sole data member is a unique_pointer to an Impl. The Impl class is private so it can have any data members you like without complicating your header.