Can a union in C++ have a member function? How do union with data members and member functions exist if an object is created?
If I suppose yes, then are they feasible an
I just added some more things to @maraguida example. I wrote it as a response just to heve more room. It illustrates that not only member functions, but also static member functions and operators can be added.
#include
union x
{
int t;
float f;
int k( ) { return t * 42;};
static int static_k( ) { return 42;};
float k_f( ) { return f * 42.0f;};
unsigned char operator []( unsigned int );
};
unsigned char x::operator []( unsigned int i )
{
if ( i >= sizeof( x ) )
return 0;
return ( ( unsigned char * )&t )[ i ];
}
int main( )
{
x y;
y.t = x::static_k( );
std::cout << "y.t\t= " << y.t << std::endl;
std::cout << "y.f\t= " << y.f << std::endl;
std::cout << "y.k( )\t= " << y.k( ) << std::endl;
std::cout << "x::static_k( )\t= " << x::static_k( ) << std::endl;
std::cout << "y.k_f( )\t= " << y.k_f( ) << std::endl;
std::cout << "y[ 0 ]\t= " << ( unsigned int )y[ 0 ] << std::endl;
std::cout << "y[ 1 ]\t= " << ( unsigned int )y[ 1 ] << std::endl;
std::cout << "y[ 2 ]\t= " << ( unsigned int )y[ 2 ] << std::endl;
std::cout << "y[ 3 ]\t= " << ( unsigned int )y[ 3 ] << std::endl;
}
It can be compiled with: g++ -Wall union_func.cpp -o union_func
The output is:
$ ./union_func
y.t = 42
y.f = 5.88545e-44
y.k( ) = 1764
x::static_k( ) = 42
y.k_f( ) = 2.47189e-42
y[ 0 ] = 42
y[ 1 ] = 0
y[ 2 ] = 0
y[ 3 ] = 0
You can, for example, put a conversion operator to another type of your need, if it make sense to your need.