Defining an object without calling its constructor in C++

后端 未结 7 2114
执笔经年
执笔经年 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 20:16

    Store a pointer to an Object rather than an actual Object

    thus:

    class Program
    {
    public:
       Object* myObject; // Will not try to call the constructor or do any initializing
       Program()
       {
          //Do initialization
          myObject = new Object(...);  // Initialised now
       }
    
    }
    

    Don't forget to delete it in the destructor. Modern C++ helps you there, in that you could use an auto_ptr shared_ptr rather than a raw memory pointer.

    0 讨论(0)
提交回复
热议问题