Search code examples
c++instantiation

C++: instantiating object that is declared in a header file


If an object is declared in a header file like this:

Object obj;

What would be the best way to instantiate it? A simple reassignment like this? Does this destroy the declared object and create a new one and can this lead to errors?

obj = Object(...);

Or should I use a pointer and create the object with new? This way i can be sure that only here the object gets created.

obj = new Object(...);

Or should the class have a init method, so the object does not get destroyed and recreated?

Would you do it any different if the object is a member of a class?


Solution

  • Object obj;
    

    already instantiates the object. SO you really should not have it in a header file

    you probably want

    Object *obj;
    

    ie a pointer to an object , then instantiate with 'new'.

    But better would be std::unique_ptr<Object>