Initialize Member Variable Which is an Object

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

  1. Use Guaranteed Initialization (Suggested)
    class Test {
    public:
    	TestImpl testImpl;
        Test(int a, int b): testImpl(TestImpl(a,b)){}
        ~Test(){}
    };
    
    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.
  2. Directly assign to the object
    class Test {
    public:
    	TestImpl testImpl = TestImpl(20, 30);
        Test(int a, int b){}
        ~Test(){}
    };
    
    Problem: Not able to assign based on the passed in value.
  3. 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.
    class Test {
    public:
    	TestImpl testImpl;
        Test(int a, int b){testImpl.a = 100;}
        ~Test(){}
    };
    
    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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值