0

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};
};
ilja
  • 109
  • 7
  • 2
    Use an initialiser list. – john Nov 28 '22 at 16:04
  • 1
    Check the answer to [this question](https://stackoverflow.com/questions/12927169/how-can-i-initialize-c-object-member-variables-in-the-constructor). I won't call it a duplicate since the question is different even though the answer is the same. – user253751 Nov 28 '22 at 16:05
  • Can you clarify some ? Do you want to pass ````pin1```` on to the constructor of ````button1```` etc. ? (What john says, move the c-tor call from the class body into a initializer list) – nick Nov 28 '22 at 16:05
  • Initializer list was what I was looking for (perfect example from @user253751). Sorry my question is a bit unclear. – ilja Nov 28 '22 at 16:12

1 Answers1

3

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)
  {
  }
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
john
  • 85,011
  • 4
  • 57
  • 81