Home > Net >  C : instantiating object that is declared in a header file
C : instantiating object that is declared in a header file

Time:09-12

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?

CodePudding user response:

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>

CodePudding user response:

Don't instantiate objects in a header file. If you include that header file in multiple translation units, you will get linker errors about duplicate ojects.

If you want to share an object with multiple units, use extern.

In the header:

extern Object obj;

In a cpp file:

Object obj(...);

  • Related