Using optionals to represent the absence of a value

suggest change

Before C++17, having pointers with a value of nullptr commonly represented the absence of a value. This is a good solution for large objects that have been dynamically allocated and are already managed by pointers. However, this solution does not work well for small or primitive types such as int, which are rarely ever dynamically allocated or managed by pointers. std::optional provides a viable solution to this common problem.

In this example, struct Person is defined. It is possible for a person to have a pet, but not necessary. Therefore, the pet member of Person is declared with an std::optional wrapper.

#include <iostream>
#include <optional>
#include <string>

struct Animal {
    std::string name;

struct Person {
    std::string name;
    std::optional<Animal> pet;

int main() {
    Person person; = "John";

    if ( {
        std::cout << << "'s pet's name is " <<
  >name << std::endl;
    else {
        std::cout << << " is alone." << std::endl;

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents