I wish to understand how I can assign member values to an optional (child) struct. Here is an example:
#include <iostream>
#include <optional>
struct Root
{
struct Parent
{
struct Child
{
int value2 = 0;
};
int value1 = 0;
std::optional<Child> child = std::nullopt;
};
std::optional<Parent> parent = std::nullopt;
};
int main() {
Root root;
root.parent.value1 = 19;
root.parent.child.value2 = 21;
// root.parent.child.value = std::optional<int>(2);
return 0;
}
Thanks!
>Solution :
if (root.parent->child.has_value()) {
root.parent->child->value2 = 21;
} else {
root.parent->child = Root::Parent::Child();
root.parent->child->value2 = 21;
}
well you can first check with .has_value() function if it is initialised or not and then assign value