Nullable Values using std::optional

Using std::optional for class members

How can I use std::optional for members in my C++ classes? Can you provide an example?

Illustration representing computer hardware

std::optional is a great choice for class members that may or may not have a value. Here's an example of how you can use it:

#include <optional>
#include <string>

class Player {
public:
  Player(const std::string& name) : name(name){}

  void set_level(int level) {
    this->level = level;
  }

  std::optional<int> get_level() const {
    return level;
  }

private:
  std::string name;
  std::optional<int> level;
};

In this example, the Player class has a name member which is always present, and a level member which is optional. The level member is not initialized in the constructor, so it starts off empty.

The set_level function sets the level member to a specific value, making it non-empty.

The get_level function returns the level member. If level has been set, it will return an std::optional containing the level value. If level has not been set, it will return an empty std::optional.

Here's how you might use this class:

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

class Player {/*...*/} int main() { Player player("Hero"); if (player.get_level()) { std::cout << "Player level: " << *player.get_level() << std::endl; } else { std::cout << "Player level not set" << std::endl; } player.set_level(5); if (player.get_level()) { std::cout << "Player level: " << *player.get_level() << std::endl; } else { std::cout << "Player level not set"; } }

This will output:

Player level not set
Player level: 5

Using std::optional for class members is a safe and expressive way to handle values that may not be present. It clearly separates the "value not set" state from any possible value the member could have, including default-constructed values.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved