You need to consider that there are two distinct constructs at work here.
Initialisation
// initialiser
// |
// name ("elem") |
// | |
// ▼▼▼▼ ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼
int elem[5] = {0, 0, 0, 0, 0};
// ▲▲▲ ▲▲▲
// \ /
// \ /
// \ /
// type (int[5])
Assignment
// new element value
// |
// name ("elem") |
// | |
// ▼▼▼▼ ▼▼▼▼▼
elem[n] = 12345;
// ▲▲▲ ▲
// | |
// | assignment operator
// |
// index (n)
Your problem has nothing to do with whether you write your code in main
or in a class definition; the problem is that you are trying to write an assignment as if it were an initialisation.
- The initialiser
{0, 0, 0, 0, 0}
simply cannot be used in an assignment
- When you write
elem[5]
instead of int elem[5]
, you're naming the 6th element of elem
, not declaring a new array of size 5 called elem
.
The error goes away when you use (0, 0, 0, 0, 0)
instead, because this is an expression that evaluates to 0
, and you can assign 0
to an element of an int
array.
Unfortunately, you're doing so to an element that does not exist, because elem[5]
is out of bounds. It's a hypothetical sixth element in a five-element array.
The inability to use initialiser syntax to assign to all of an array's elements in one fell swoop is a limitation of C and C++.
To assign to the array at an arbitrary place, you'd have to assign them one by one in a loop, or use a fill function:
std::fill(std::begin(elem), std::end(elem), 0);
…which is much better anyway.
Fortunately, you've committed another crime that's actually quite convenient: you actually do want to initialise, even though at the moment you're instead assigning inside the constructor body. To initialise class members, you must use the constructor's member-initialiser list and, as it happens, the constructor's member-initialiser list enables us to use initialiser syntax:
arr2()
: elem{0, 0, 0, 0, 0}
{}
…or, more simply:
arr2()
: elem{}
{}