1

I'm creating an Array of a Class Type (Button), and I want to have a subclass of it called ButtonMb inside the array Button Is that possible? I tried to have two different constructors and use only one Class, but since number of parameters are the same, I couln't reach anywhere.

Here is my code: for simplicity I only included header code for class declaration

typedef void (*Callback)(void);
typedef int (*CallbackInt)(void);

class Button {
  public:
    OneButton _pin;

    Button(uint8_t pin, Callback click=NULL, Callback longCl=NULL, Callback dblCl=NULL);
  
    void loop();
};

class ButtonMb : public Button {
  public:
    CallbackInt _pinState;

    ButtonMb(CallbackInt pinState, Callback click=NULL, Callback longCl=NULL, Callback dblCl=NULL);
    
    void loop();
};

Button buttons[2] = {
  Button(14),
  ButtonMb([](){return slaves[0].getState("A15");)
};

Any help?

NOTE: I'm using Arduino, so code can be limited.

1
  • Nope, sorry, arrays in C++ don't work this way. Commented Jan 27, 2021 at 23:08

1 Answer 1

1

Instead of using array of objects, you can create array of pointers. Pointers of base class can point to derived classes, so you can have pointers to objects of different types in one array.

Sign up to request clarification or add additional context in comments.

3 Comments

like this? Button* buttons[2]={Button(14), ButtonMb(...)};
Close, it would be better if you first allocated those buttons on heap, now you tried to insert objects instead of pointers pointing to the objects. Button* b_ptr = new Button(14); Button* mb_ptr = new ButtonMb(...); Button* buttons[2]={b_ptr, mb_ptr);
There may be no need for dynamic allocation. For example, Button button(14); ButtonMb buttonmb(...); Button* buttons[]={&button, &buttonmb};. If you find yourself needing dynamic allocation, consider using a smart pointer to manage the allocation: std::unique_ptr<Button> buttons[]={std::make_unique<Button>(14), std::make_unique<ButtonMb>(...)};. documentation for std::unique_ptr and documentation for std::make_unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.