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

Advertisements
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 :

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.

Leave a Reply Cancel reply