Array of OneWire instances

I need to have two (or more) OneWire instances in an array. I am able to set it up in the following way:

OneWire  ds1(7);
OneWire  ds2(8);
OneWire *oneWireBus[2];
void setup2() {
  oneWireBus[0] = &ds1;
  oneWireBus[1] = &ds2;
}

However, I would like to create these objects without setting them in a function. I have tried stuff like, which does not work.

OneWire *oneWireBus[] {
    &OneWire(7),
    &OneWire(8)
  };

How can I do this?

What are you trying to do here and why ?

OneWire *oneWireBus[] = {
    new OneWire(7),
    new OneWire(8)
  };

The problem you were having is that your two objects are temporaries, they only exist in the scope of the initializer list, so taking the address of them doesn't make sense, since said address would be invalid outside of the list. Instead you need to use dynamic allocation (i.e. the "new" operator) which creates the object and returns a pointer to it. This works because the object is never deleted automatically, only by you the programmer using the delete operator, e.g.

delete oneWireBus[0];

Alternatively, you could not use pointers, as below, then you won't need to manage the objects manually, they'll get automatically deleted when the array goes out of scope.

OneWire oneWireBus[] = {
    OneWire(7),
    OneWire(8)
  };

(You can drop the equals signs in C++ '11 and beyond, but the Arduino IDE does not default to C++ '11)

Thats a really thorough and well explained answer. Thanks a lot :slight_smile: