Correct declaration of a property in a class

I added two properties to the Periods.h file:

unsigned int *numberOfPeriods;
unsigned int *periods;

I added the following code to the Periods.cpp file

numberOfPeriods = new unsigned int[3] {
    5, 2, 3
  };

  periods = new unsigned int[3][numberOfGroups][numberOfLeds] {
    {
      {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}
    },
    {
      {0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}
    },
    {
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}
    },
  };

The numberOfPeriods property works correctly, but the periods property causes a compilation error
Could you please tell me how to correct it?

Don't you think it would help if we saw the actual error message???

1 Like

You'd make the compiler happy by doing the following, but it would still be nonsense.

  periods = (unsigned int *)(new unsigned int[3][numberOfGroups][numberOfLeds] {
    {
      {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}
    },
    {
      {0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}
    },
    {
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}
    },
  });

I can't imagine any benefit to allocating those two arrays dynamically like you're doing now... why don't you define them without using pointers?

2 Likes

Agreeing with @cotestatnt

Seems all these are constant including numberOfGroups or numberOfLeds if you can hardcode the array’s content.

You should just make them and the array constant and shared by all instances and not use new at all.

(If each instance needs an array, then just create it as an instance variable. Don’t use a pointer and new)

2 Likes