C++ Academy · Lesson

Accessing optional Values

Use value_or and has_value.

Lesson 2 of 413 steps

Accessing optional Values is a free C++ Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

Dereference Operator

The fastest way to read an optional is *opt, but only when you are sure it holds a value, there is no check.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> o = 10;
    if (o) std::cout << *o << "\n";
}

The value() Method

opt.value() returns the value, but throws std::bad_optional_access if the optional is empty. Use it when an empty optional is a real error.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> o;
    try { std::cout << o.value() << "\n"; }
    catch (const std::bad_optional_access&) { std::cout << "empty!\n"; }
}

value_or for Defaults

opt.value_or(fallback) returns the contained value if present, otherwise the fallback. No branching, no exceptions.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> o = std::nullopt;
    std::cout << o.value_or(-1) << "\n"; // -1
}

value_or with Real Data

A common use is supplying a default for missing configuration or lookups.

#include <iostream>
#include <optional>
#include <string>
std::optional<std::string> lookup(bool found) {
    if (found) return std::string("Pro");
    return std::nullopt;
}
int main() {
    std::cout << lookup(false).value_or("Free") << "\n";
}

Arrow Operator

For optionals of class types, opt->member accesses members directly (again assuming non-empty).

#include <iostream>
#include <optional>
#include <string>
int main() {
    std::optional<std::string> o = std::string("hello");
    if (o) std::cout << o->size() << "\n";
}

Guard Before Access

The safe idiom is: check, then use. Combining the check and access avoids both exceptions and undefined behavior.

#include <iostream>
#include <optional>
int main() {
    std::optional<int> o = 7;
    if (o.has_value()) {
        int x = *o;
        std::cout << x * 2 << "\n";
    }
}

Init-Statement in if

You can declare and check in one line using an if init-statement, keeping the optional scoped to the branch.

#include <iostream>
#include <optional>
std::optional<int> find() { return 3; }
int main() {
    if (auto v = find(); v.has_value())
        std::cout << *v << "\n";
}

Transform (C++23)

Monadic helpers like transform apply a function only if a value is present, returning a new optional. This chains computations cleanly.

and_then for Chaining

and_then (C++23) calls a function that itself returns an optional, flattening the result, ideal for steps that may each fail.

Choosing an Accessor

Use value_or when you have a sensible default, value() when emptiness is an error worth an exception, and */-> only after an explicit check.

Avoid Unchecked Dereference

Never call *opt without confirming the optional is non-empty. It is undefined behavior and a common source of crashes.

Quick Check

Check your understanding of optional access.

Recap

You learned how to access optionals:

  • * and -> after a check.
  • value() throws on empty.
  • value_or supplies a default.
  • Monadic transform/and_then chain operations (C++23).
Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Accessing optional Values” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Accessing optional Values”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Accessing optional Values”?

Use value_or and has_value. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Accessing optional Values” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Representing Absence with optional
  2. Accessing optional Values
  3. std::expected Basics
  4. Error Handling Patterns
← Back to C++ Academy