ubadub
ubadub

Reputation: 3880

In a C++ class, do you have to initialize member variables that are arrays?

For example:

class Cls
{
private:
    int x;
    int y;
    int arr[10];

public:
    Cls();
};

Cls::Cls() : x(0), y(0) {}

My understanding is that an uninitialized array will have garbage values. As long as I don't write code that expects the array to have a specific value before filling it, is there any issue with not initializing the array? Or do I need something like this as the constructor:

Cls::Cls() : x(0), y(0), arr() {}

Upvotes: 1

Views: 377

Answers (2)

Tas
Tas

Reputation: 7111

If your logic is that you definitely won't write code that accesses them before setting them, then no you don't need to initialise them. If for instance you straight up did not use the array at all, you could simply leave them unitialised.

However it is simply best to initialise them since there's no reason not to, even if you initialise them to bad values. What might happen is although you always write before reading now, that may change in the future. 6 months down the track someone may refactor something, and now a read happens before a write. Because that's undefined behaviour, maybe your program will seem to function correctly, or it might work on their machine but crash on another. If you initialise them, you just won't get these problems.

Perhaps your concern is that 0 is a valid value and you don't want your program to accidentally get that value, you'd rather make it clear it's not properly initialised, but with undefined behaviour you could get 0 or some other valid value or a crash, and it may be inconsistent. You will probably thank yourself if you just initialise everything properly.

The C++ police or a compiler won't stop you from doing so, and your program can still be well formed, but you may as well guarantee it by just initialising them.

Upvotes: 1

Brian Bi
Brian Bi

Reputation: 119219

The constructor of Cls is not required to initialize the array member. Failing to initialize it will leave the elements with indeterminate values. Contrary to popular belief, objects with indeterminate values aren't merely objects whose values are unspecified; as a matter of fact, attempting to read them, before first writing definite values to them, causes undefined behaviour. For this reason, it's generally advisable to set the values as soon as possible.

Upvotes: 3

Related Questions