How to return and error in constructor?

Hello,
I understand that Arduino cannot use exceptions and that there is no return type for constructors, so my question is:

If the constructor detects an error, how is that error condition returned to the main() program?

Specifically for my issue, I want to create a class to control an I2C device. The constructor accepts the address of the I2C device as an argument, then uses the wire.beginTransmission() / wire.endTransmission() pair to make sure the device is available. If there is an error returned by the wire.endTransmission(), the constructor should somehow notify the main() that it failed.

Thanks,
Kevin

Add a start() or begin() method that can return an error.

Set a global variable to an error condition.

BTW, it would do no good to tell main() that there is an error, since you never get there with an arduino.

KeithRB:
Set a global variable to an error condition.

Or, don't....
No offense, but that is suggesting a bad object model. If you're going through the trouble of creating a nice encapsulated class, relying on a global variable is a really bad idea.

On a desktop compiler you might throw an exception in the constructor, but that has it's own set of issues/considerations. And on the AVR compiler exceptions would create a huge amount of over-head that is not a good idea either.

Arch's suggestion is a good one then. Focus your constructor on the guaranteed to work items (remember pin numbers, etc.) and create a start()/begin()/init() whatever function that does the work that may fail. Those functions should return an error/boolean to indicate success.

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.

"Or, don't...."

Oops, my C is showing. errno, anyone?

You could create an error condition variable in the class and use a getError() method to read it.

Is that better?

Though the start method idea is better.

Thank you for all your tips and suggestions - the start() method should do the trick. Thanks!

the start() method should do the trick.

Except that the Arduino convention is to call the function begin() (as in Serial.begin(), EthernetServer.begin(), etc.).