Using this with array of pointer in class constructor c++

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?

1 answer

  • answered 2021-09-11 18:07 Ghasem Ramezani

    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);
      }
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum