How to Create Array of Objects?

This seems very easy, but I can’t figure it out. I’d like to create 3 objects, and keep their references in an array. My plan is to use 3 OneWire buses, so it would obviously help to keep their Object references in an array.

I originally thought something like this would work

OneWire buses[3];
for(i = 0; i < 3; i++) {
  // Create 1W objects on pins 8,9,10
  buses[i] = new OneWire(i + 8);

…but this doesn’t seem to work. After some searching I found syntax like this:

int[] myArray = new int[3];

…although I can’t get this to work (at least with arduino-0017), and don’t see how I’d instantiate the objects with different parameters.

I’m a bit lost - can anyone help me? Thanks!

int[] myArray = new int[3];

That looks like Java. C++ equivalent is int myArray[3];

OneWire buses[3];

I see no problem with this, what was the error you got?

I guess I should have posted my code etc. earlier…? :wink:

Okay, here’s my code:

#include <OneWire.h>

OneWire buses[3];

void setup() {

void loop() {

…which has a compile error:

error: no matching function for call to 'OneWire::OneWire()'
note: candidates are: OneWire::OneWire(uint8_t)

I can’t seem to find a way to declare the reference without actually creating the object, and then can’t instantiate three objects with different arguments.

Any ideas?

//I have not checked to see if pins 2,3,4 is usable with this library.
OneWire buses[3] = {

Perfect - that works nicely. I'm up and running now - thank you!

Just out of interest, is there a way to declare an object reference without instantiating it (either singularly, or in an array)?

is there a way to declare an object reference without instantiating it

I thought that was the advantage of using references over using pointers - you can’t have an uninitialised reference, so you have to have an instance of the object.

You should be able to create a pointer to an object as follows:

OneWire *ptrOneWire;

Creating one however doesn't make sense until you make it point to an instance.

You can also write a function that take an object reference as a parameter:

void ReadOne(OneWire &ow)
  // access any OneWire instance passed as parameter