Constructor code

I’ve just solved a problem I had with code within a constructor. Although the problem is now solved, can anyone give me an explanation.

I had a working sketch and a class library. The sketch created an object (based on my class) in the declarations section (i.e. before the setup() bit). This worked fine until I added some code to the constructor, as soon as I did this the sketch wouldn’t even start. I solved the problem by adding a begin() section to the class and moving the code that was in the constructor to begin(). I then called the begin() from within the setup(). It all works fine again.


I’ve put code within other constructors before without problems, the only difference this time is that my code involved calls to multiple objects and other classes. Most of the stuff I normally add to constructors is just to initialise a few variables.

Whats the difference here?


You can not access objects that depend on the arduino init call to have occurred. Such as the Serial static objects.

IF you post your code it will be easier to point at the exact problem.

Thanks, what is the 'init' call?

Although the constructor code is only one line, it creates a file on an SD card, so involves calls to half a dozen library's - including it here probably wouldn't help.

This is the actual Arduino program, not the sketch:

#include <WProgram.h>

int main(void)
	init(); //see line 167 in wiring.c

	for (;;)
	return 0;

What's the difference between the 'actual arduino program' and a 'sketch'?

Sounds like the begining of a whole new subject for me, is there a link to some information on this you could send me?



What's the difference between the 'actual arduino program' and a 'sketch'?

A C/C++ program has a "main", which you will notice is missing from any Arduino sketch. The Arduino provides "main" and "init" invisibly, as well as (most) function prototypes.