Using optionals to represent the failure of a function

suggest change

Before C++17, a function typically represented failure in one of several ways:

* e.g. Calling a function `Delegate *App::get_delegate()` on an `App` instance that did not have a delegate would return `nullptr`.
* This is a good solution for objects that have been dynamically allocated or are large and managed by pointers, but isn't a good solution for small objects that are typically stack-allocated and passed by copying.

In this example, John is given two pets, Fluffy and Furball. The function Person::pet_with_name() is then called to retrieve John’s pet Whiskers. Since John does not have a pet named Whiskers, the function fails and std::nullopt is returned instead.

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

struct Animal {
    std::string name;

struct Person {
    std::string name;
    std::vector<Animal> pets;
    std::optional<Animal> pet_with_name(const std::string &name) {
        for (const Animal &pet : pets) {
            if ( == name) {
                return pet;
        return std::nullopt;

int main() {
    Person john; = "John";
    Animal fluffy; = "Fluffy";
    Animal furball; = "Furball";
    std::optional<Animal> whiskers = john.pet_with_name("Whiskers");
    if (whiskers) {
        std::cout << "John has a pet named Whiskers." << std::endl;
    } else {
        std::cout << "Whiskers must not belong to John." << std::endl;

Feedback about page:

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

Table Of Contents