Strange error with c++ class constructor

Hi,

I try to create a c++ class. This is very simple class for the moment.
Led class, header :

#ifndef capteur_h
#define capteur_h
#include "Arduino.h"
class Led
{
  public:
    Led(int aPin);
};
#endif

Cpp file

#include "capteur.h"

Led::Led(int aPin)
{
  SerialUSB.println("here");
}

And ino file

#include "capteur.h"

Led my_led(); 

void setup() {
  SerialUSB.begin(115200);
  while (!SerialUSB) ;
  SerialUSB.println("Setup");
}
void loop() {
  // put your main code here, to run repeatedly:
}

In my ino file if I do a

Led my_led();

it's work but if I do a

Led my_led(1);

it's doesn't work everything compiled but when I put the code in my bord I've nerver got here message in my console (setup or here messages) and I got an error with the ide I loss the connexion with the board "error when open port" I must reset the board, and put the code without parameters in my constructor, anyone know why? I really don't understand the code is really simple :confused:

isn't pin 1 the TX pin?

No, no pin I just try to use c++ class, I got the same error if I put 1, 2 or 10. But it's works if I create my object in my setup function (with and without parameters).
Why I can't create my object before setup function ??

You are calling the class constructor before serial is initialised

Try this

.ino

#include "capteur.h"

Led my_led(13);

void setup()
{
  Serial.begin(115200);
  while (!Serial) ;
  Serial.println("Setup");
  my_led.init();
}
void loop()
{
}

.h

#ifndef capteur_h
#define capteur_h
#include "Arduino.h"
class Led
{
  public:
    Led(int aPin);
    void init();
};
#endif

.cpp

#include "capteur.h"

Led::Led(int aPin)
{
}

void Led::init()
{
  Serial.println("in init");
}

Or..

#include "capteur.h"

Led* my_led;  // A pointer to your object.

void setup() {
  SerialUSB.begin(115200);
  while (!SerialUSB) ;
  SerialUSB.println("Setup");
  my_led = new Led(13);         // Dynamically create the class (at the correct time)
}
void loop() {
  // put your main code here, to run repeatedly:
}

-jim lee

Global object constructors are called before setup() so before your Serial.begin(). That might explain why you can't use Serial.print() in the constructor of a global object. That is also why a lot of library objects have a .begin() function. The Arduino core is not initialized until just before setup() is called and millis(), micros(), delay(), Serial... won't work until the core is initialized.