Class member without a default constructor

后端 未结 3 1343
栀梦
栀梦 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:39

    Member objects are always initialized before entry into the body (the part between the curly braces) of the constructor. If you don't mention a member in the initializer list, it gets default constructed. So mention it!

    B::B(int j) : _a(factoryA(0 < j)) { };
    

    This calls the function factoryA with the argument value true if j is greater than 0 and false otherwise, and initializes the member _a with the value returned by that call.

提交回复
热议问题