Program hanging before setup() when accessing static member

I'm attempting to write a generic logging class for a program running on a Arduino Pro Mini. In that class I've attempted to create a singleton which everything else in the program uses. Unfortunately when I do that setup() never seems to be called. I've trimmed my code down to the following short program that illustrates the problem:

class Foo {
 public:
  Foo() {
    Serial.begin(115200);
    Serial.println("Serial begin done");
    Serial.flush();
  }

  static Foo* Get() {
    if (instance_ == nullptr) {
      instance_ = new Foo();
    }
    Serial.print("Count is ");
    Serial.println(++count_);
    Serial.flush();
    return instance_;
  }

 private:
  static Foo* instance_;
  static int count_;
};
Foo* Foo::instance_ = nullptr;
int Foo::count_ = 0;

Foo* global_foo_1 = Foo::Get();
Foo* global_foo_2 = Foo::Get();
Foo* global_foo_3 = Foo::Get();
Foo* global_foo_4 = Foo::Get();

void setup() {
  Serial.println("In setup");
  Serial.flush();
}

void loop() {
  Serial.println("In loop");
  Serial.flush();
}

The output of this program is only:

Serial begin done
Count is 0
Count is 1
Count is 2
Count is 3

What happens between finishing setting up variables in the global scope and the setup() call? I'm guessing there is a crash in that code but I don't really know what it could be.

Note: I'm writing the debugging class mainly because its fun and that's what personal projects are for :). I'm only saving a few lines of code in a few call sites and likely adding to the overall program size but I'm having fun!

Any help would be greatly appreciated!

Warmly,

It's not crashing. Add this line to the start of your setup function:

Serial.begin(115200);

It's a bad idea to run any hardware code in a constructor because that runs before init() is called. I think what happens in your code above is the Serial.begin() call sets up the serial but then that work is undone before setup() is called.

That was exactly the problem and adding the Serial.begin to the top of setup() fixed it. For posterity it wasn't that setup was never being called it was that the Serial.flush() call was likely hanging because as pert pointed out Serial wasn't setup correctly.

Thanks for the help!

You're welcome. I'm glad to hear it's working now. Enjoy!
Per