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

Can a union be initialized in initializer-list? If so, how? If not, why?

union value {
    int i;
    bool j;
};
class Json {
    public:
        Json(int i): m_value.i(i) {};//error
        m_value.i = i;  //correct
    private:
        value m_value;
};

Can a union be initialized in initializer-list? If so, how? If not, why not?

>Solution :

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

If you have a compiler that conforms to the C++20 Standard (or later), then you can use a designated initializer in the "initializer list", to initialize (and, thus, activate) either member of your union, like so:

union value {
    int i;
    bool j;
};

class Json {
public:
    Json(int iarg) : m_value{ .i = iarg } { }
    Json(bool barg) : m_value{ .j = barg } { }
private:
    value m_value;
};

However, before C++20, designated initializers were not part of C++ (though they have been part of C for some time); in such cases, you can only initialize the first member of the union:

union value {
    int i;
    bool j;
};

class Json {
public:
    Json(int iarg) : m_value{ iarg } { } // Sets m_value.i to iarg
private:
    value m_value;
};

Note also that I have used the {...} syntax for the initializer, rather than the (...) ‘old style’ and that I have used an argument name that is not the same as a union member.

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