C++C++17Code SnippetLanguage FeatureLearn C++

Tutorial: Easily Learn To Use optional In Modern C++ On Windows

young lady typing on keyboard of laptop in living room

Optional definition (std::optional) manages an optional contained value, i.e. a value that may or may not be present. This class template comes with C++17 standard, it is used with CLANG and other C++ compilers which has this standard. A common use case for optional is the return value of a function that may fail. Any instance of optional<T> at any given point in time either contains a value or does not contain a value. If an optional<T> contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined.

C++ Builder supports C++17 standards with its CLANG compiler and Bcc Compiler. Optional can be used to define any type of variables as below;

An optional variable can be checked by has_value() method if it has a value or not.

Value optional variable can be obtained by value() property and or value_or(0) method that returns 0 if no value. This C++ Builder VCL Windows application example below explains all;

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.


Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial

Free C++Builder Community Edition

About author

Dr. Yilmaz Yoru has 35+ years of coding with more than 30+ programming languages, mostly C++ on Windows, Android, Mac-OS, iOS, Linux, and some other operating systems. He graduated and received his MSc and PhD degrees from the Department of Mechanical Engineering of Eskisehir Osmangazi University. He is the founder and CEO of ESENJA LLC Company. His interests are Programming, Thermodynamics, Fluid Mechanics, Artificial Intelligence, 2D & 3D Designs, and high-end innovations.
Related posts
C++C++11C++14C++17C++20

What Is The Stack (std::stack) In Modern C++?

C++C++11C++14C++17C++20Learn C++

What Is The Queue (std::queue) In Modern C++?

C++C++11C++14C++17Learn C++SyntaxTemplates

What Are The Logical Operation Metafunctions In Modern C++?

C++C++14C++17C++20Learn C++

What Are The Deprecated C++14 Features In C++17?

Worth reading...
Introduction To C++ Windows Development With C++Builder