Representing Absence with optional
Avoid null pointers.
Representing Absence with optional is a free C++ Academy lesson on CoddyKit. This is lesson 1 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.
The Problem with Null
Returning a sentinel like -1 or a null pointer to mean "no value" is fragile and easy to misuse. std::optional<T> represents "a value, or nothing" explicitly. Include <optional>.
#include <iostream>
#include <optional>
int main() {
std::optional<int> maybe = 42;
std::cout << *maybe << "\n";
}An Empty Optional
Default-constructing an optional, or assigning std::nullopt, gives an empty one that holds no value.
#include <iostream>
#include <optional>
int main() {
std::optional<int> empty;
std::optional<int> also = std::nullopt;
std::cout << empty.has_value() << " " << also.has_value() << "\n";
}Checking for a Value
Call has_value() or use the optional directly in a boolean context to test whether it contains something.
#include <iostream>
#include <optional>
int main() {
std::optional<int> o = 5;
if (o) std::cout << "has value\n";
if (o.has_value()) std::cout << "yes\n";
}Optional as a Return Type
Functions that might fail to produce a result are a perfect fit. Return the value on success, std::nullopt on failure.
#include <iostream>
#include <optional>
std::optional<int> half(int n) {
if (n % 2 == 0) return n / 2;
return std::nullopt;
}
int main() {
auto r = half(10);
if (r) std::cout << *r << "\n";
}Reading the Value
Use *opt or opt.value() once you know it has a value. Dereferencing an empty optional with * is undefined behavior.
#include <iostream>
#include <optional>
int main() {
std::optional<std::string_view> name = "Ada";
if (name) std::cout << *name << "\n";
}Self-Documenting Signatures
An std::optional return type tells the caller, at a glance, that the function may not produce a result, no comments needed.
#include <iostream>
#include <optional>
#include <string>
std::optional<std::string> getEnvName(bool present) {
if (present) return std::string("CONFIG");
return std::nullopt;
}
int main() { std::cout << getEnvName(true).has_value() << "\n"; }Resetting an Optional
Call reset() to make an optional empty again, or assign std::nullopt.
#include <iostream>
#include <optional>
int main() {
std::optional<int> o = 99;
o.reset();
std::cout << o.has_value() << "\n"; // 0
}Constructing In Place
emplace constructs the contained value directly inside the optional, avoiding an extra copy.
#include <iostream>
#include <optional>
#include <string>
int main() {
std::optional<std::string> o;
o.emplace("built in place");
std::cout << *o << "\n";
}Optional vs Pointer
A raw pointer can be null but says nothing about ownership and risks dangling. An optional owns its value by value and clearly signals "maybe absent" without heap allocation.
Optional of References?
std::optional stores values, not references. To optionally refer to an existing object, store a pointer or use std::optional<std::reference_wrapper<T>>.
When to Reach for Optional
Use it for lookups that may miss, parsing that may fail, or settings that may be unset. The next lesson covers safe ways to access the contained value.
Quick Check
Check your understanding of std::optional.
Recap
You learned std::optional basics:
- Represents "a value or nothing" without sentinels or null.
- Empty via default construction or
std::nullopt. - Check with
has_value()or a boolean test. - Ideal as a return type for fallible lookups.
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 “Representing Absence with optional” lesson free?
Yes — any 3 lessons of the C++ Academy learning path, including “Representing Absence with optional”, 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 “Representing Absence with optional”?
Avoid null pointers. 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 1 of 4.
How long does the “Representing Absence with optional” 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
- Representing Absence with optional
- Accessing optional Values
- std::expected Basics
- Error Handling Patterns