I am programming a certain class, which can be instanced multiple times. Some functions of this class are intended to traverse every instance.
In my particular case, I am doing a valves controller. Each valve takes a time to open, hence, I need to call a Valve.loop() function which would call a .loop function on each particular instance of Valve class.
Another case that could exemplify what I want, would be a sprite class; where the call to a Sprite.draw() function would call the .draw function on each instance of Sprite.
The objective is to be able to just call ClassName.staticFunction() instead of having to store the instances in array and then iterate each.
As a side note, I am working on Arduino. I think, however that this is applicable in any other case.
This is the code I am trying (I rewrote it from scratch to remove the irrelevant things)
Valve.h
Code:
#ifndef VALVE_H
#define VALVE_H
#define valvesAmount 8
class Valve{
private:
void runCallback();
public:
int id;
static int count;
void setCallback(void (*callback)(int id));
unsigned long ends=0;
int openControlPin;
Valve(int _openControlPin);
void checkState();
void open();
static Valve *valves [valvesAmount];
static void loop();
};
int Valve::count=0;
Valve::Valve(int _openControlPin){
openControlPin= _openControlPin;
id=count;
Valve::valves[id]=this;
count++;
}
void Valve::runCallback(){
//I would run some callbacks
}
void Valve::loop(){
for(int vn=0; vn<Valve::count; vn++){
Valve *current=Valve::valves[vn];
current->checkState();
}
}
void Valve::checkState(){
unsigned long now=millis();
if(ends){
if(now>ends){
ends=0;
runCallback();
}
}
}
void Valve::open(){
unsigned long now=millis();
ends=now+3000;
}
#endif
problem_code.ino
Code:
#include "Valve.h"
void setup(){
new Valve(1);
new Valve(2);
new Valve(3);
new Valve(4);
}
void loop(){
Valve::loop();
}
In my mind, it should work. Instead, I get a (linker?) error saying:
Code:
[...] AppData\Local\Temp\ccWvHJ6n.ltrans0.ltrans.o: In function `Valve::Valve(int)':
sketch/Valve.h:26: undefined reference to `Valve::valves'
sketch/Valve.h:26: undefined reference to `Valve::valves'
I have tried many things and sought online a lot, but I remain clueless.
This is my first post. I have read the guidelines, and I hope it is well adjusted to the communities expectations. Thanks!