Calling Serial.begin() within C++ constructor

I'd like to use the serial port within a library implemented as a C++ class. What is the proper way to call the Serial.begin() function? I tried putting it in my object constructor, but the port was not properly initialized. I finally created a begin() function within my class which called Serial.begin(). Is this the correct way?

This did not work:

MyClass::MyClass(void)
{
  Serial.begin(19200);
}

// instantiate object
MyClass myObject;

void setup()
{
}

void loop()
{
  // code using myObject goes here...
}

This works:

MyClass::MyClass(void)
{
}

void MyClass::begin(uint16_t u16BaudRate)
{
  Serial.begin(u16BaudRate);
}

// instantiate object
MyClass myObject;

void setup()
{
  // initialize communication baud rate
  myObject.begin(19200);
}

void loop()
{
  // code using myObject goes here...
}

That's what I prefer. Having a "begin" gives the person using the library control over when (and if) the initialization is performed. It also makes it easier to provide a default constructor (a very good thing in my opinion).

Note: The following may not be correct. I'm relying soley on my memory.

There's a known problem with Serial and constructors. The bottom line is that constructors are called too early in the initialization process. There's a fix in the forum.

There's a known problem with Serial and constructors. The bottom line is that constructors are called too early in the initialization process.

There is actually a known problem with all arduino-functions that involve Timers (Interrupts?) and constructors. For instance the delay() function also doesn't work in a constructor.
Using a custom begin()-function in your code is the right way handle this.
Eberhard

Eberhard

Thanks for the replies. I'll stick with the begin() function.

Rx