Category Archives: C++

Fun with implicit conversions

What does this print?

Without much thought, you’d answer:

But you would be wrong! This program actually prints lots of “As” until the stack overflows and the program crashes!


A simple fix is to declare the two functions before defining them, so the second foo with be visible inside the first one.

The real question though, it why the string was being converted to an optional<string> in the first place.

Let’s examine the header file of boost::optional.

Aha! The constructors are defined as follows:

As you can see, the constructors are not marked explicit . What this means is that a value of type T can be implicitly converted to boost::optional<T>, which is exactly what happened in our case.

Implicit conversions are bad (most of the time) when constructors accept exactly one argument.
This seems to be one of those times.
Why the designer of boost::optional decided not to mark the constructors as explicit is beyond me.