Problem
I have a class with a member as an object of another class. I want to initialize it and use it.
class Test {
public:
TestImpl testImpl;
}
Solution
- Use Guaranteed Initialization (Suggested)
Problem: In the case if the object member variable require computation before initialize, the order of execution will cause the problem. It is pretty hard to have the data ready before the guaranteed initialization is called.class Test { public: TestImpl testImpl; Test(int a, int b): testImpl(TestImpl(a,b)){} ~Test(){} };
- Directly assign to the object
Problem: Not able to assign based on the passed in value.class Test { public: TestImpl testImpl = TestImpl(20, 30); Test(int a, int b){} ~Test(){} };
- For objects, if nothing assign to the object member, their default constructor is called. For example, for std::string, the default constructor sets it to an empty string. If the object’s class does not have a default constructor, it will be a compile error if you do not explicitly initialize it.
Problem: can only access to public field. Need setter to access protected and private field. Not a standard way of initialization however can solve the problem in the first solution.class Test { public: TestImpl testImpl; Test(int a, int b){testImpl.a = 100;} ~Test(){} };