Skip to content
luni64 edited this page Oct 23, 2020 · 1 revision

Initializing arrays of class objects

If you have a class with a default constructor (parameter less constructor) you can easily declare arrays of objects of this class. Here an example showing how to do this with Servos

#include "Servo.h"

Servo servos[5];         // array of 5 Servo objects

void setup()
{
   servos[0].attach(3);  // attach pins to the Servos
   servos[1].attach(7);
   //...
}

However, if the constructor of your class needs parameters you need to pass them as shown below for the Encoder class. The Encoder constructor requires two pin numbers for phase A and phase B respectively.

#include "Encoder.h"

Encoder encoders[]{{1,2}, {4,7}, {0,15}}; // constructs 3 encoders at pins (1,2), (4,7) and (0,15)
constexpr int nrOfEncoders = sizeof(encoders) / sizeof(encoders[0]);

void setup(){}

void loop()
{
    for (int i = 0; i < nrOfEncoders; i++)
    {
        Serial.println(encoders[i].read());
    }
    delay(200);
}

Back | Fun with modern c++

Using initializer lists

Initializer lists can be useful if you need to do something for a list of arbitrary objects. The following example shows how to set the pinMode of a bunch of pins to output:

void setup()
{
    constexpr uint8_t pinA = 3, LED = 13, STP = 7;

    for(uint8_t pin : {pinA, LED, STP}) // for each pin in the initializer list
    {
        pinMode(pin, OUTPUT);
    }
}

You can also use initializer lists as parameters to functions. Let's define a enhancement for the pinMode function which takes a list of pins instead of only one.

void pinMode(std::initializer_list<uint8_t> pins, uint8_t mode){
    for(uint8_t pin : pins){
        pinMode(pin, mode);
    }
}

// usage:
void setup(){
    constexpr uint8_t pinA = 3, LED = 13, STP = 7;
    pinMode({pinA, LED, STP}, OUTPUT);
}

Back | Fun with modern c++

Clone this wiki locally