Is there really an Anonymous class/struct in C++?

  anonymous, c++

I’m confused by many websites: People there refer to a class/struct as Anonymous when it has no name for example:

struct{
   int x = 0;
}a;

I think the example above creates an Unnamed struct but not an Anonymous struct. I think an Anonymous struct/class doesn’t have a name nor a declarator after the close-curly brace that ends the class body and before the semi-colon that ends the class definition:

class { // Anonymous class
   int x_ = 0;
}; // no delcarator here

And of course the standard refuses such declaration above because it is ill-formed.

  • unions can be Unnamed or Anonymous:

      union{
         char unsigned red_;
         char unsigned green_;
         char unsigned blue_;
         long unsigned color_ = 255;  
      } color;
    

In this example above I’ve declared an unnamed (but not an anonymous) union and this is similar to the class/structs above.

  • A union can be Anonymous:

      // cannot be declared in a namespace except adding `static` before the keyword `union` which makes the linkage of the unnamed object local to this TU
      /*static*/ union{ // Anonymous union
         char unsigned red_;
         char unsigned green_;
         char unsigned blue_;
         long unsigned color_ = 255; ;
      }; // no declarator
    
      green_ = 247; // ok accessing the member data green_ of the Anonymous union
    
  • Above I’ve declared an Anonymous union and the code works just fine. The reason is that the compiler will automatically synthesize an object of that Anonymous union and we can access its members directly. (although there are some restrictions).

  • I think the compiler disallows Anonymous class/struct because it doesn’t automatically creates an object of that type.

So are my thoughts correct? if not please guide me. Thank you!

Source: Windows Questions C++

LEAVE A COMMENT