Anonymous classes in c++

This code compiles quite normally.

class 
{ 
   public:
   //...
} anonymous;

Why and for what purposes are unnamed classes used?

Author: αλεχολυτ, 2016-11-29

2 answers

To begin with, I want to draw your attention to the fact that in C++ there are no anonymous classes with the keywords class or struct. You are confusing the concepts of unnamed class and anonymous class. These concepts are different and have different semantic meanings. In your question, you are talking about unnamed classes.

Named class definitions define named types. Using this name, you can explicitly declare members of such a class, in the declaration of which there is a class type specifier, objects of this type, or, for example, function parameters. In addition, if the name has an external binding, it will mean the same entity in different compilation units if you include the declaration of this name in these compilation units.

In an unnamed class, it is not possible, for example, to declare constructors, destructors, operators that have a return value type, or parameter types that include the class name.

You also, for example, you can't declare class data members that are pointers or references to class objects.

In an unnamed class, you are not allowed to declare static members of the class data.

From the C++ standard (9.4.2 Static data members)

4 [ Note: There shall be exactly one definition of a static data member that is odr-used (3.2) in a program; no diagnostic is required. -end note ] Unnamed classes and classes contained directly or indirectly within unnamed classes shall not contain static data members.

For example, how do you declare a list node if you can't declare a data member in the definition of that node that is a pointer to the next or previous node?

So the capabilities of unnamed classes are very limited.

Unnamed classes are usually used as nested classes of other classes, or as local classes when the unnamed class type thus introduced is not required outside of the scope where this unnamed class is defined.

 12
Author: Vlad from Moscow, 2016-11-29 17:51:46

This feature is left for the sake of compatibility with the old (C without pluses code). In C, unnamed and named structures are almost equivalent, so a large amount of code uses: tyedef struct { int a; int b; } my_type; (so that you can write my_type instead of struct my_type at the point of use of the type. In C++, unnamed classes have no practical use.

 3
Author: Chorkov, 2016-11-29 19:01:07