when to initialize serial port

Hi Folks, I wrote an own library that uses HardwareSerial as a parameter. I did something like this:

class MyClass {
  HardwareSerial *m_puart;
  public:
  void println(char *);
  MyClass(HardwareSerial &uart, uint32_t baud);
};
MyClass::MyClass(HardwareSerial &uart, uint32_t baud) : m_puart(&uart){
  m_puart->begin(baud);
}
void MyClass::println(char *str) {
  m_puart->println(str);
}

And I've used like this:

MyClass myclass(Serial,115200);
void setup() {
}

void loop() {
  myclass.println("something");
  Serial.println("something else");
  delay(1000);
}

This does work on arduino mega but does not work on arduino nano. On nano I need to re-call a begin-like method of MyClass that does the m_puart.begin(). Please explain why. Thanks in advance! D

You must initialize it in the setup. That’s why the Serial library itself does it there. So just make a begin method in you’re library as well. So it becomes

MyClass myclass(Serial);
void setup() {
  myclass.begin(115200); //(or myclass.begin() but then you have to save the baudrate)
}

void loop() {
  myclass.println("something");
  Serial.println("something else");
  delay(1000);
}

Thank you for quick reply! I see it that your way is the right way. What confuses me that my 'illegal' code worked for me on an arduino mega...

What confuses me that my 'illegal' code worked for me on an arduino mega...

Perhaps the constructors are called in a different order. One should never rely on the order that constructors will be called in. One should write code so the order doesn't matter.