union
{
int v1;
int test ( int p) { return p+p;}
} uniontest;
void main ( void)
{
uniontest.v1=5;
int res = uniontest.test(10);
printf("res=%d\n",res);
}
All Ok. The compiler translate code to program with no errors or warning.
If running the program work correctly and show the right result 20.
In the ansi c++ directive don't describe the function as elements of a union.
What is the utility of function into a union ? I don't know.
It seems the microsoft compiler use the union at the same mode of struct.
bye to all
Angelo
So you can't think of any use of a union with a member functions.
How is this related to the compiler and why you consider this a
bug?
According to C++ Standard `union', `struct' and `class' keywords
declare a class, though unions have some limitations. Nonetheless,
a union can have member functions, constructors and destructors as
any other class.
Alex
In addition to what Alex said, to see the potential utility of a union, try
defining one with two member variables of different types and instantiate it
to then see the amount of memory allocated to your new type. The point of a
union is to conserve memory where only one of two or more variables needs to
be used at any single point in time.
> According to C++ Standard `union', `struct' and `class' keywords
> declare a class, though unions have some limitations. Nonetheless,
> a union can have member functions, constructors and destructors as
> any other class.
>
> Alex
Member functions - yes, but not constructors or destructors, as far as I
recall. With memory shared among variables, it would be difficult to figure
out which ones are meant (for initialisation purposes).
Unions can have ctors and dtors, it is their members that can not.