Jason
Jason

Reputation: 115

Constructors in union causing undefined behavior?

I get the values for NumericType Values (10, 3.1416, 20) to be 20, 3.1416, 20 after the object has been constructed. is the behaviour for constructors in a union defined?

union NumericType
{
    NumericType() {}

    NumericType(int i, double d, long l)
    {
        iValue = i;
        dValue = d;
        lValue = l;
    }

private:
    long        lValue; 
    int         iValue; 
    double      dValue;
};


int main()
{
     union NumericType Values ( 10, 3.1416, 20 );
}

Upvotes: 1

Views: 179

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75130

What you're doing doesn't make sense. Because it's a union, you're assigning to the same area of memory 3 times. Because you assign to lvalue in the constructor last, that's what everything remains at. All three variables are at the same location and occupy the same memory (with the exception of dValue which takes up 4 more bytes than the other two).

You probably want a struct, not a union (because in structs, all variables are seperate and setting one to something won't affect others).

Here's a good visualization (keep in mind this block is just one 8 byte chunk of memory, not 3):


(source: microsoft.com)

Upvotes: 2

James McLeod
James McLeod

Reputation: 2406

Bear in mind that the elements in a union share memory, so having a constructor which initializes all of them will throw away information.

That said, this is not valid C++.

Upvotes: 1

Related Questions