2

So for exemple if I have a struct like this:

struct Client_t {
std::string name;
uint16_t id;
};

Would it be better to have a constructor on this struct

Client_t(std::string name, uint16_t id) :
    name(std::move(name)), id(id) {}

and initialise it like this:

Client_t* client = new Client_t(name, id)

or is it better to do it like this:

Client_t* client = new Client();
client->name = name;
client->id = id;
Gabriel Martins
  • 179
  • 1
  • 6
  • 3
    It is always best to initialise objects to valid values, so use a constructor. Also, some types do not support assignment, so you cannot use the second method if your class contains them. –  Aug 11 '18 at 13:25
  • Frankly, it would be better to (a) use construction per Neil's comment, and (b) lose the manual memory management entirely, opting for either automatic variable, or smart pointers if required. – WhozCraig Aug 11 '18 at 13:37
  • The second version is slower, because first it constructs a default `name`, then assigns it. With this simple example, this is likely get optimized away, but for more complex cases, the compiler may not be able to do that. – geza Aug 11 '18 at 14:30

2 Answers2

2

Here you have a few good reasons to always use a constructor:

  • You may want to validate the parameters;
  • If you suddenly add more required fields to your struct/class, you can just modify the constructor(s) signature and let the compiler tell you where the code should be fixed. Without a constructor, this could be much harder to track. Some IDEs could help with this task, but the compiler is your friend here;
  • You may want to debug the initialization of your objects, so you can add breakpoints inside your constructors (instead of adding them to random parts of your code);
  • In some cases you may want to forbid unwanted implicit type conversions, so you would use the explicit keyword in your constructor(s). What does the explicit keyword mean?
  • You may want to add different flavors to your initialization. For example, you may want a constructor that receives parameters as rvalues, and another constructor that receives them as references or by value.

As a final thought, your code will be cleaner and easier to debug and maintain if you use constructors.

HugoTeixeira
  • 4,674
  • 3
  • 22
  • 32
0

The whole point of a constructor is to initialize the object into a functional state.

If the object can be considered fully formed and functional without some of the initialization being done, then sure, you can leave those bits to be set afterwards (maybe). But if something is required for the object to function then it should be done by the constructor so callers cannot forget to do it later.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70