Initialising arrays in class constructor

Hi everyone,

A newbie question. I have created a class (simplified version), with the .h as below:

class LimitlessLED {
  public:
    LimitlessLED();
    void sendUDP(byte *cmd);
    void setBrightness(int level);
    void setColour(int col);
    void setBrightness(int gp, int level);
    void setColour(int gp, int clr);
    int control(String cmd);

  private:
      byte white_ALL_off[2];
};

With the constructor in .cpp:

LimitlessLED::LimitlessLED() {
  this->white_ALL_off  = {0x39,0x00};
}

I get compilation error with error: assigning to an array from an initializer list

What is the problem with initialising default array variables in a constructor?

Thank you for your guidance! :smile:

Regards,
Tim

Great question Tim! If you know the initial values of the array at compile time:

  • You should declare them once static for the class instead of once for every copy of the object.
  • You should put it in flash with const to save on precious SRAM.
  • You can just directly define the array values before object construction.

Example:

class LimitlessLED {
  private:
    static const byte white_ALL_off[2];
};

const byte LimitlessLED::white_ALL_off[] = { 0x39, 0x00 };

Hope that helps! If not, don’t hesitate to ask more questions.

Cheers!

2 Likes

Thank you for taking your time to answer my question, @zachary! :smile: