Accessing The Stored Value

This lesson goes into detail on the different ways to access optional type values.

Probably the most important operation for optional (apart from creation) is the way you can fetch the contained value. You have already seen it working with operator*.

However, here are several options:

  • operator* and operator-> - if there’s no value the behaviour is undefined!
  • value() - returns the value, or throws std::bad_optional_access
  • value_or(defaultVal) - returns the value if available, or defaultVal otherwise

To check if the value is present you can use the has_value() method or just check if (optional) as optional is contextually convertible to bool.

Here’s an example:

Get hands-on with 1200+ tech skills courses.