title: Is a union in C++ actually a class?
body: <p>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)</p>
  
  <pre><code>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&amp; operator=(float data) {fData = data;return *this;};
    unMember&amp; 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;
  }
  </code></pre>
  
  <p>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? </p>
  
  <p>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?</p>
  
  <p>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?</p>