Can't make an array of ezButton

Hello all,

I've been trying to make an array of ezButtons, but my CPP days are very far behind.
This is how I tried :

ezButton *Buttons = new ezButton[5];  // create an array of ezButton objects
Buttons[0] = ezButton(2); // create ezButton object that attach to pin 2
Buttons[1] = ezButton(3); // create ezButton object that attach to pin 3
Buttons[2] = ezButton(4); // create ezButton object that attach to pin 4
Buttons[3] = ezButton(5); // create ezButton object that attach to pin 5
Buttons[4] = ezButton(6); // create ezButton object that attach to pin 6

But I get an error : "no matching function for call to 'ezButton::ezButton()'
Apparently, there is no suitable constructor for such a call in the ezButton.cpp file.
Is this possible ?
Should I modify the ezButton library and add a constructor ? (and how ? As I said, my cpp is VERY rusty, like 15 years old.)
Or should I just copy my code 5 times, which I find very stupid and time consuming, which isn't the goal of programming to begin with...

TIA.

I would try something like

ezButtons Buttons[] = { 2, 3, 4, 5, 6 };

maybe another level of braces is needed, around the initialization list (one item here).

ezButtons Buttons[] = { {2}, {3}, {4}, {5}, {6} };
1 Like

ezButtons Buttons[] = { 2, 3, 4, 5, 6 };

^^ That compiled on first try, thank you very much !!!

And it is so much shorter to write. :grinning:

1 Like

So we can't use pointers to objects in Arduino or is it just the way the library is written ?

What makes you say that?
"Arduino" is simply C++ with some pre-pre-processing
(Whatever arduino.cc say about it being a "language")

1 Like

You absolutely can use object pointers, but they are not needed here,
and for dynamic arrays rather hard to use, as you have experienced.

You wanted an array of button objects, its elements can be initialized individually.

If you use new for arrays, you have to have a default constructor (with no parameters).

1 Like

And, the ezButton class doesn't have one. Makes it even more difficult:

	public:
		ezButton(int pin);
		ezButton(int pin, int mode);
1 Like

That's what I noticed, and initially thought I'd modify the ezButton class to add a default constructor, but the solution I've been proposed was so much simpler that I realised my idea was pointless.

Unlike in other languages like Java, you should almost never use the new keyword in C++.

If you need a fixed-size array, simply create it on the stack as shown in the answer posted by Whandall.
If you need a dynamically allocated array, use an std::vector, which allows you to create array of types without a default constructor (with all the caveats of dynamic allocation on microcontrollers, of course).

1 Like

Please see example in this: For beginners: The simple way to program for multiple buttons [code example]

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.