3

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
Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
Sijith
  • 3,740
  • 17
  • 61
  • 101

2 Answers2

5

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
  • 23,277
  • 13
  • 73
  • 121
4

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
  • 93,612
  • 16
  • 138
  • 200