Arduino instantiating object arrays

Hello,

I ran into a minor issue today. I was wondering if it was possible to make an array of objects since you could do it in Java. I wanted to make an array of SoftwareSerial declarations and after some searching the web I wrote this in the sketch:
SoftwareSerial softSerial[2] = { SoftwareSerial(5, 4), SoftwareSerial(3, 2) };
Rather than this:
SoftwareSerial softSerial1(3, 2);
SoftwareSerial softSerial2(5, 4);
The array was to simplify code as I could use a for loop rather than retyping both lines every time and using a conditional to check which one I was using. However, I tried it out today and it seems that the second instantiation overrides the first. In other words the only softSerial pins that work are 2 and 3. If I switch the numbers they work but again only the second instantiation of SoftwareSerial works.

Any thoughts or ideas on why it may not be working? It compiles fine which is why I figured nothing was wrong until I opened up the Serial Monitor. And yes I checked both elements of the array and only the second displays data.

Do you mean something like this:

SoftwareSerial softSerial1(3, 2);
SoftwareSerial softSerial2(5, 4);

SoftwareSerial softSerial[2] = { softSerial1, softSerial 2 }

Ok now I get what you meant. Don’t I have to instantiate softSerial1/2 first though? Wouldn’t the first line give an error because softSerial1/2 were not declared. Same as if I wrote:

Serial.print(x) without ever typing before it int x = number

I’m not getting anywhere. I tried empty array but it gives an error if I don’t fill it. I assume an array of objects cannot be empty but has to be filled when created. It’s getting confusing because I see many examples of object arrays such as:

LED ledarray[5] = { LED(1), LED(2), … LED(5) }
I don’t see why an array of SoftwareSerial only allows the last one to “exist” and not the others before it which appear to be non-existent.

edit I got some help with this and turns out only 1 softSerial port can be listened to at a time. To swap ports to listen you would use the command softSerial[1].listen() and now you can read data from that port.

You probably need to instantiate two SoftwareSerial objects when declaring the array and initialize them at a later step.

I was thinking more like this:
SoftwareSerial softSerial[2] = { softSerial1, softSerial2 } //declare

softSerial[0].SoftwareSerial(3, 2); //init
softSerial[1].SoftwareSerial(5, 4);

But I have not tried the code so they syntax may need more love.

you are right. Perhaps only creating an empty array first would be the best solution.

Thanks you for posting the solution. We are glad you could solve your problem.