A junior developer asked me if it was possible to overload assignment operators for a union with POD arguments such that the corresponding data type within the union would get written to when an instance of the union is assigned to variable of that type. I replied that I did not think so, but then played around with the following code. To my surprise this code actually compiled (using g++ version 4.6.3 on Ubuntu 12.04)
union unMember
{
float fData;
unsigned int uiData;
unMember():uiData(0) {};
unMember(float data):fData(data) {};
unMember(unsigned int data):uiData(data) {};
operator float() {return fData;};
operator unsigned int() {return uiData;};
unMember& operator=(float data) {fData = data;return *this;};
unMember& operator=(unsigned int data) {uiData = data; return *this;};
float GetFloat() const {return fData;};
};
int main () {
float fTest = 1.0;
unsigned int uiTest = 10;
unMember data = fTest;
unMember data2 = uiTest;
unMember data3 = data2;
float f = data.GetFloat();
return 0;
}
This has made me realise that I know pretty much nothing at all about unions (at least in the context of C++ rather than C) as I really did not expect to be able to define member functions for a union in this way. The above code suggests to me that in C++ a union is implemented internally as a class, but is that in fact the case in the C++ standard or is this just some quirk of the g++ compiler?
Also, because this has really shaken my understanding of what a union is, I would welcome any comment on whether it is advisable to implement member functions for unions in this way? Is there anything inherently unsafe in the above implementation of my union?
In the past I have only used unions within a container class that has an indicator variable that stores what type has actually been written to in the union and to be honest I thought that was their primary use. Is it actually common to overload constructors etc for unions in this way?
Is a union in C++ actually a class?
Yes. In C++ a union is a class: a special kind of class.
C++11: 9 Classes (p5):
A union is a class defined with the class-key union; it holds only one data member at a time
Is it actually common to overload constructors etc for unions in this way?
A union is a special class with some restrictions:
9.5 Unions (p2):
A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class.
11 Member access control (p3):
Members of a class defined with the keyword
class
areprivate
by default. Members of a class defined with the keywordsstruct
orunion
arepublic
by default.
So, you can overload constructors, destructors and operators similar to as you can do in a class.
来源:https://stackoverflow.com/questions/23932389/is-a-union-in-c-actually-a-class