Apologies if this has been discussed before but I couldn't find anything.
I have written a simple LED class. For illustration (it is actually a bit more complex) but it goes something like;
class LED {
LED(byte pin);
private:
int _pin;
};
And the constructor is simply;
LED::LED(byte pin) {
_pin = pin;
};
and I create a global instance of this class at the top of my code thus;
LED redLED(5);
It is necessary to create this as a global object because (a) I can't create the object in the setup() function because it would go out of scope and (b) I can't create in the loop() function because I don't want to create an infinite number of these objects.
This all seems to work OK but it just leaves me wondering exactly when this constructor gets executed? I suppose that it must be before setup()?
Answered!
Many thanks to all the respondents. So when using the Arduino IDE the build process must silently insert the main() procedure. I was not aware that it did this. I guess that most of the time you can get away with not knowing when the global constructors are called.
It is good practice (I think) to create a "wrapper" class for all/any external (or perhaps internal) hardware devices that are connected to your arduino. And it is thus perhaps tempting (but risky) to do initialisation work in the constructor.
So given what I now know, it is better to create an "init()" method for such classes that can be called from setup(). Even if just to do the the pinmode() call.
Thanks again.
begin()
is the canonical name for such a method.