C++ Structs – Should Constructors Be Added?

cobject-orientedprogramming practices

We often use c++ structs to define data structure as opposed to class which can be a complete module with member methods. Now deep down, we know they both are the same (loosely speaking).

The fact that we often use/treat structs as data only entities creates this urge that we not add default constructors as well. But constructors are always great, they make things simpler and help eliminate errors.

Would it be frown upon if add default constructors to my data structures?

Does implementing default constructor also make the struct Non-POD (plain old data type) provided other criteria are met?

To put things in perspective, consider a simple example but in reality the struct would be much larger.

struct method
{
    char    name[32];
    float   temperature;
    int     duration;
};

Every time I create a method, I have to worry about (to say the least) if I forgot to set some value. Imagine I forget to set temperature and apply the method to system which is now a random high value and causes mayhem. Or I forgot to set duration and now the method applies itself for an unknown high duration.

Why should I take responsibility to initialize the object every time instead of implementing its constructor which guarantees it?

Best Answer

Sometimes it's appropriate to add constructor to a struct and sometimes it is not.

Adding constructor (any constructor) to a struct prevents using aggregate initializer on it. So if you add a default constructor, you'll also have to define non-default constructor initializing the values. But if you want to ensure that you always initialize all members, it is appropriate.

Adding constructor (any constructor, again) makes it non-POD, but in C++11 most of the rules that previously applied to POD only were changed to apply to standard layout objects and adding constructors don't break that. So the aggregate initializer is basically the only thing you lose. But it is also often a big loss.