Skip to content

Validated Creation with optional

The Course
•
35 min study

Some inputs cannot create a valid object. A duration of 0 minutes, an empty title or the text "4x" read from a file should not turn into a task at all. A constructor is a poor place to say so: it has no return value, and this course compiles without exceptions, so a constructor that receives bad input can only build a bad object or stop the program.

The traditional workaround is a sentinel: a special value such as -1 or 0 that means "no result". Sentinels cause two problems. They can collide with real values (is 0 "no duration" or "zero minutes"?), and nothing forces the caller to check for them, so -1 flows into a total as if it were data.

std::optional<T> from <optional> solves both. It holds either a T or nothing, and the "nothing" is a separate state, written std::nullopt, that no T can be confused with. A function that returns std::optional<int> tells every caller, in its type, that the answer may be missing.

Predict and run

duration accepts 1 through 180 and returns nothing for anything else. What are the two printed lines?

Predict before running C++
#include <iostream>
#include <optional>

std::optional<int> duration(int value) {
    if (value < 1 || value > 180) { return std::nullopt; }
    return value;
}

int main() {
    auto result = duration(25);
    if (result) { std::cout << *result << "\n"; }
    std::cout << duration(0).has_value() << "\n";
    return 0;
}
Check your prediction
Text
25
0

return value; wraps the int in an optional automatically, and return std::nullopt; returns an empty one. In a condition, an optional is true when it holds a value, so if (result) and if (result.has_value()) mean the same thing. *result then reads the stored int. The second line prints 0 because std::cout shows false as 0.

Check before you read

Reading an empty optional with * or -> is undefined behavior. The operator does no check at all; it simply reads the storage where a value would be. The program may print an old number, crash, or behave differently after an optimization, so the bug may never show up in testing:

C++
auto missing = duration(0);
std::cout << *missing << "\n"; // Undefined behavior: missing is empty.

There are three safe ways to get at the value:

  • Test, then read: if (result) { use(*result); }. This is the usual form, and it makes the missing branch visible.
  • Use a fallback: result.value_or(0) returns the stored value or the fallback. Use it only when the fallback really is the right answer, for example "no time logged" really meaning 0 minutes.
  • Avoid value() here: result.value() checks, but on an empty optional it throws an exception. This course builds with -fno-exceptions, so that throw becomes an immediate program abort.

A present zero is not absence

The point of optional is that "no value" and "the value 0" are different states. The program below parses text two ways. The sentinel version returns 0 for both bad text and the text "0", and its caller cannot tell them apart.

Sentinel versus optional C++
#include <iostream>
#include <optional>
#include <string>

int parse_or_zero(const std::string& text) {
    if (text.empty() || text.size() > 3) { return 0; }
    int value = 0;
    for (char ch : text) {
        if (ch < '0' || ch > '9') { return 0; }
        value = value * 10 + (ch - '0');
    }
    return value;
}

std::optional<int> parse(const std::string& text) {
    if (text.empty() || text.size() > 3) { return std::nullopt; }
    int value = 0;
    for (char ch : text) {
        if (ch < '0' || ch > '9') { return std::nullopt; }
        value = value * 10 + (ch - '0');
    }
    return value;
}

int main() {
    for (const std::string text : {"0", "abc"}) {
        auto parsed = parse(text);
        std::cout << text << ": sentinel " << parse_or_zero(text) << ", optional "
                  << (parsed ? std::to_string(*parsed) : "none") << "\n";
    }
    return 0;
}
Text
0: sentinel 0, optional 0
abc: sentinel 0, optional none

Both versions limit the text to three digits before multiplying, so value cannot overflow an int. Signed overflow is itself undefined behavior, which is why the length check comes first instead of after the loop.

Factories: the constructor's missing "no"

The pattern the project uses combines optional with the previous lesson's private members. The class keeps its constructor private and offers a public static member function, usually called create, that validates the arguments and returns std::optional<Task>. A static member function belongs to the class rather than to an object, so callers write Task::create(...) before any task exists. Because create is a member, it may call the private constructor; ordinary code may not. Every task that exists therefore passed through one validation rule.

This handles invalid domain input, which is an ordinary event in a program that reads files. It does not handle running out of memory: that is outside what this course promises to recover from, and an optional cannot report it. The checkpoint that follows builds a full factory.

Practice

Exercise

Your turn

Write std::optional<int> parse_minutes(const std::string& text) that accepts one to three decimal digits whose value is 1 through 180. Reject empty text, longer text, any non-digit and out-of-range values. Print each case, showing none when the text is rejected:

Text
"25" -> 25
"180" -> 180
"0" -> none
"181" -> none
"" -> none
"4x" -> none
"1000" -> none
Parse checks passed

Assert at least the 0 and 180 cases.

Your workspace C++
#include <cassert>
#include <iostream>
#include <optional>
#include <string>

// Write parse_minutes here.

int main() {
    // Try "25", "180", "0", "181", "", "4x" and "1000".
    return 0;
}
Hint 1: the idea

Reject the shape first (length and digits), then compute the number, then check the range. Each step can return std::nullopt on its own, and the value is only returned at the end.

Hint 2: a first step

Start with if (text.empty() || text.size() > 3) { return std::nullopt; }. Build the number with value = value * 10 + (ch - '0'), which is safe because three digits cannot overflow.

Show one solution
Run the solution C++
#include <cassert>
#include <iostream>
#include <optional>
#include <string>

std::optional<int> parse_minutes(const std::string& text) {
    if (text.empty() || text.size() > 3) { return std::nullopt; }
    int value = 0;
    for (char ch : text) {
        if (ch < '0' || ch > '9') { return std::nullopt; }
        value = value * 10 + (ch - '0');
    }
    if (value < 1 || value > 180) { return std::nullopt; }
    return value;
}

int main() {
    assert(!parse_minutes("0"));
    assert(parse_minutes("180") == 180);
    for (const std::string text : {"25", "180", "0", "181", "", "4x", "1000"}) {
        auto minutes = parse_minutes(text);
        std::cout << '"' << text << "\" -> " << (minutes ? std::to_string(*minutes) : "none") << "\n";
    }
    std::cout << "Parse checks passed\n";
    return 0;
}
Text
"25" -> 25
"180" -> 180
"0" -> none
"181" -> none
"" -> none
"4x" -> none
"1000" -> none
Parse checks passed

parse_minutes("180") == 180 works because comparing an optional with a plain value is false when the optional is empty, so it never reads missing storage. The length check rules out "1000" before any arithmetic, which keeps the multiplication far from overflow. Every exit except the last returns std::nullopt, so a value only escapes after passing all three checks. The checkpoint applies the same shape to a class: a private constructor behind a create factory.

Was this article helpful?

Your response is saved on this device.