0

I have an abstract class A and a class B with the constructor:

B(A &a) {...}

Now, I create these objects in the main program as follow:

int main(){
  std::unique_ptr<A> a = make_A();//don't mind make_A()
  if(a==null)
    a = make_default_A();
  B b (*a); 
}

Now I created a class which setups the system:

class System{
public:
  System();
private:
  B b;
  std::unique_ptr<A> a;
}

And the constructor is:

System(){
  a = make_A();
  if(a==null)
    a = make_default_A();
  b(*a);
}

Obviously this is wrong because I can't call B's constructor as in the code above, but I can't figure out how to do this. The only solution that came to my mind is to use std::unique_ptr<B> b; instead of B b; and then call b = make<B> (*a);.

justHelloWorld
  • 6,478
  • 8
  • 58
  • 138

1 Answers1

1

It should be:

class System{
public:
  System() : a(make_A()), b(*a) {} // use initializer list for constructor
private:
  // Fix order of members to initialize in correct order.
  std::unique_ptr<A> a;
  B b;
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302