Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: How to assign member value in nested optional struct?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading