Defining an object without calling its constructor in C++

后端 未结 7 2168
执笔经年
执笔经年 2020-12-23 19:26

In C++, I want to define an object as a member of a class like this:

Object myObject;

However doing this will try to call it\'s parameterle

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 19:51

    You can use a pointer (or a smart pointer) to do that. If you do not use a smart pointer, do make sure that your code free memory when the object is deleted. If you use a smart pointer, do not worry about it.

    class Program
    {
    public:
       Object * myObject;
       Program():
          myObject(new Object())
       {
       }
       ~Program()
       {
           delete myObject;
       }
       // WARNING: Create copy constructor and = operator to obey rule of three.
    }
    

提交回复
热议问题