begin() in constructor

Hi.

In How to return and error in constructor? - #5 by system - Programming Questions - Arduino Forum
PeterH says:

You usually don't want the constructor to interact directly or indirectly with hardware or anything in the Arduino runtime, since static constructors are called before the Arduino runtime has initialised the hardware. Use a begin() or similar method to initialise the wire interface and return any status information you need it to.

I suppose I understand what it means but ...

In some of my classes, the last constructor line is a call to begin() and these is where the hardware initialization (inputs/outputs, pullups, etc) takes place. So long it seems to work.

Should I just construct the class and invoke the begin() method immediately (from outside the class)? Of course, this one has the advantage of allowing some error return but sometimes there is no error to return.

Indeed to construct and initialize (from outside) in every class has the advantage of a sort of procedure standardization.

Thanks

Yes. The normal order (a) create an object from the class then (b) use its begin method to initialise things like pins etc.
You should limit the initialisation in the constructor because not all the Arduino environment has been set up at the time the constructor is invoked.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.