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?

4
  • 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? Commented Sep 11, 2021 at 17:59
  • Does this answer your question? Expression must be a modifiable L-value Commented Sep 11, 2021 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". Commented Sep 11, 2021 at 18:05
  • It seems to me that What is this weird colon-member (" : ") syntax in the constructor? might be useful reading. Commented Sep 11, 2021 at 18:08

1 Answer 1

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);
  }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, very detailed answer!
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<Toy*>.
@JaMiT It is fixed code, I have no choice mate :(
@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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.