Home > Enterprise >  Add class members dynamically
Add class members dynamically

Time:11-29

For my Arduino project, I want to have a class called Buttons, that has six EasyButton instances as members. I want to pass the pins of the EasyButton instances to the Buttons constructor. How can I instantiate the six EasyButton members of my Buttons class in the Buttons constructor?

#include <EasyButton.h>


uint32_t debounce_time = 200;
bool pullup_enable = true;
bool active_low = true;

class Buttons
{
private:

public:
  Buttons(uint8_t pin1, uint8_t pin2, uint8_t pin3, uint8_t pin4, uint8_t pin5, uint8_t pin6);
  // do the following in the constructor.
  EasyButton button1{pin1, debounce_time, pullup_enable, active_low};
  EasyButton button2{pin2, debounce_time, pullup_enable, active_low};
  EasyButton button3{pin3, debounce_time, pullup_enable, active_low};
  EasyButton button4{pin4, debounce_time, pullup_enable, active_low};
  EasyButton button5{pin5, debounce_time, pullup_enable, active_low};
  EasyButton button6{pin6, debounce_time, pullup_enable, active_low};
};

CodePudding user response:

This can be done with an initialiser list

class Buttons
{
private:

public:
  Buttons(uint8_t pin1, uint8_t pin2, uint8_t pin3, uint8_t pin4, uint8_t pin5, uint8_t pin6);
  EasyButton button1;
  EasyButton button2;
  EasyButton button3;
  EasyButton button4;
  EasyButton button5;
  EasyButton button6;
};

  Buttons::Buttons(uint8_t pin1, uint8_t pin2, uint8_t pin3, uint8_t pin4, uint8_t pin5, uint8_t pin6)
      : button1(pin1, debounce_time, pullup_enable, active_low),
        button2(pin2, debounce_time, pullup_enable, active_low),
        button3(pin3, debounce_time, pullup_enable, active_low),
        button4(pin4, debounce_time, pullup_enable, active_low),
        button5(pin5, debounce_time, pullup_enable, active_low),
        button6(pin6, debounce_time, pullup_enable, active_low)
  {
  }
  • Related