I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.
Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.
#include <stdlib.h>
class Train {
public:
int numOfCars;
void init();
void move();
};
void Train::init() {
//code intentionally removed
}
void Train::move() {
//code intentionally removed
}
const int trainCount = 2;
Train train1;
Train train2;
Train trains[trainCount] {train1, train2};
void setup() {
Serial.begin(9600);
train1.numOfCars = 5;
train1.init();
train2.numOfCars = 5;
train2.init();
}
void loop() {
for(int n = 0; n < trainCount; n++) {
Train tr = trains[n];
Serial.println(tr.numOfCars); //always prints 0
tr.move();
}
}