I tried to assign an array of pointer to nullptr.
class ToyBox
{
private:
Toy *toyBox[5];
int numberOfItems;
public:
ToyBox()
{
this->numberOfItems = 0;
this->toyBox = {}
}
}
An error throw at this in this->toyBox:
expression must be a modifiable lvalueC/C (137)
Any suggestion to corrected?
CodePudding user response:
You can only Initialize arrays in that way: Assign a single value to array. But in the constructor you could/must use Member Initialize List:
class ToyBox
{
private:
Toy *toyBox[5];
int numberOfItems;
public:
ToyBox() :
toyBox{nullptr}
, numberOfItems(0)
{
}
};
With C , It's better to use std::array
instead of raw C-Array:
related: CppCoreGuidlines: ES.27
class ToyBox
{
private:
std::array<Toy*, 5> toyBox;
int numberOfItems;
public:
ToyBox() :
toyBox({nullptr})
, numberOfItems(0)
{
}
};
Or (I think) better:
ToyBox() : numberOfItems(0)
{
std::fill(toyBox.begin(), toyBox.end(), nullptr);
}