Class member without a default constructor

后端 未结 3 1346
栀梦
栀梦 2020-12-07 02:16

Suppose I have a class A without a default constructor, a factory method factoryA that returns an object of type A, and a class B that has A as its member. I know that in th

3条回答
  •  醉酒成梦
    2020-12-07 02:30

    It is not entirely clear to me why so if someone could explain that to me it would be great.

    For classes[*], the _a = factoryA(true); line calls _a.operator=(factoryA(true)). Calling a member function on _a requires _a to already be initialised. So if it weren't a compile-time error, it still wouldn't be valid.

    Also, what if the parameter to A's constructor needs to be computed inside of B's constructor, say by querying a database or something of that nature? Is there a way to use the setup below without providing A with a default constructor?

    As long as A has a copy or move constructor, you can initialise it with a function return value, and that function can do anything you want, even using different constructors for A depending on the arguments provided.

    class B {
    private:
      A _a;
      static A getA(int i);
    public:
      B(int j) : _a(getA(j)) {
      }
    };
    
    A B::getA(int j)
    {
      if (j > 0)
        return factoryA(true);
      else
        return factoryA(false);
    }
    

    [*] I know, there are exceptions.

提交回复
热议问题