views:

77

answers:

2

Hi,

I have two doubts, please help me on this:

  1. Is it possible to define a class inside union
  2. Is it possible to define a class without class name
+5  A: 

1 - yes with restriction that class has no constructor or destructor 2 - yes

Following code aggregates both as an example:

union MyUnion
{
    class 
    {
        public:
        int a;
        int b;
    } anonym_access;
    double align;

};

int main()
{
    MyUnion u; //instance checks if it is compileable
}
Dewfy
+4  A: 

Is it possible to define a class inside union

A union can contain any plain-old-data (POD) type. Types with a non-trivial constructor or destructor are non-POD and, therefore, cannot be used in a union. For such types, you can use boost::variant.

Is it possible to define a class without class name

Yes, it is possible to create anonymous classes, as in:

class
{
     // ... body of class ...
} name_of_instance;
Michael Aaron Safyan
http://stackoverflow.com/questions/2253878/why-does-c-disallow-unnamed-structs-and-unions
Johannes Schaub - litb