Itβs not entirely clear to me why this is so if someone can explain that it would be great for me.
For classes [*] string _a = factoryA(true); calls _a.operator=(factoryA(true)) . Calling a member function on _a requires that _a already initialized. Therefore, if this is not a compile-time error, it will still be invalid.
Also, what if the constructor parameter A must be computed inside constructor B, for example, by querying a database or something like that? Is there a way to use the setting below without providing A to the default constructor?
As long as A has a copy or move constructor, you can initialize it with the return value of the function, and this function can do anything you like, 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)) { } }; AB::getA(int j) { if (j > 0) return factoryA(true); else return factoryA(false); }
[*] I know there are exceptions.
source share