Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with no name

I read this about class in the C++ standard document:

A class is a type. Its name becomes a class-name (9.1) within its scope.

class-name: identifier template-id

I found this grammar for an identifier in the C++ Standard:

 2.10 Identifiers
 identifier: nondigit
 identifier nondigit
 identifier digit

 nondigit: one of universal-character-name 
 _ a b c d e f g h i j k l m n o p q r s t u  v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
 digit: one of 0 1 2 3 4 5 6 7 8 9

Now I tried doing this:

class
{
public:
  int i;
};

and it compiles fine without any name.

Can anyone give me an explanation regarding this? Isn't it a violation of the grammar specified for an identifier?


Nawaz had asked a follow up question regarding the standard compliance of the code I had given. Those interested can check it out here.

like image 979
Amit Tomar Avatar asked Nov 23 '25 07:11

Amit Tomar


2 Answers

The grammar goes

class-specifier:
    class-head { member-specification_opt }

class-head:
    class-key attribute-specifier-seq_opt class-head-name class-virt-specifier-seq_opt base-clause_opt
    class-key attribute-specifier-seq_opt base-clause_opt

class-key:
    class
    struct
    union

In your case, the second production of class-head is used -- no class-name is involved.

like image 56
avakar Avatar answered Nov 24 '25 20:11

avakar


The identifier is omitted entirely, so the question of correct grammar for the identifier is moot. Nothing in the description says the identifier must be present. Anonymous classes are probably allowed for consistency with C struct rules, which allows constructs such as:

typedef struct { int i; } Foo;

struct { int x, y; } points[] = { {1, 2}, {3, 4} };

I don't think I've ever seen this done for a class.

like image 27
Marcelo Cantos Avatar answered Nov 24 '25 21:11

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!