0

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?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Tan Nguyen
  • 323
  • 2
  • 14
  • 1
    `this->toyBox = {}` What do you expect it to do? Also, `Toy *toyBox[5];` is not a pointer to an array, but array of pointers, is that intended? – Quimby Sep 11 '21 at 17:59
  • Does this answer your question? [Expression must be a modifiable L-value](https://stackoverflow.com/questions/6008733/expression-must-be-a-modifiable-l-value) – Mureinik Sep 11 '21 at 17:59
  • @Quimby I think the expectation of that line is given at the beginning of the question: "assign an array of pointer to nullptr." Not the best phrasing, but I believe that is supposed to mean "assign `nullptr` to the pointers in an array". – JaMiT Sep 11 '21 at 18:05
  • It seems to me that [What is this weird colon-member (" : ") syntax in the constructor?](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) might be useful reading. – JaMiT Sep 11 '21 at 18:08

1 Answers1

1

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);
  }
Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32
  • Thanks, very detailed answer! – Tan Nguyen Sep 11 '21 at 18:09
  • 1
    Since `ToyBox` tracks the number of items, `std::vector` might be a better choice than `std::array`. In fact, an even better approach might be `using ToyBox = std::vector`. – JaMiT Sep 11 '21 at 18:11
  • @JaMiT It is fixed code, I have no choice mate :( – Tan Nguyen Sep 14 '21 at 07:37
  • 2
    @TanNguyen Since you are stuck with "fixed code", it doesn't really matter to you what alternatives are mentioned, does it? Besides, the goal of this site it to be a repository of knowledge (in question-and-answer format) for future visitors. It's just a (often occurring) bonus when a good answer for future visitors happens to also help the original asker. Improving an answer for the benefit of future readers is good. (In my mind, the improvement would still mention `std::array` as an improvement, then mention `std::vector` as the next step up.) – JaMiT Sep 14 '21 at 23:20