João Afonso João Afonso - 6 months ago 60
C++ Question

C++ Grammar production: class-head

Below you'll find the definition of the grammar production class-head in [class]/1:


  class-key attribute-specifier-seqopt class-head-name
class-virt-specifieropt base-clauseopt

  class-key attribute-specifier-seqopt

At the end of the paragraph you'll find the following:

A class-specifier whose class-head omits the class-head-name
defines an unnamed class. [ Note: An unnamed class thus can’t be
final. —end note ]

From the above, I gather that the grammar for a named class, i.e., a class with a class-head-name, is given by the first definition above, and the grammar for an unnamed class is given by the second definition.

A simple question: wouldn't be possible to replace both definitions above by the first one, simply by substituting class-head-name with class-head-nameopt in it?

Or to be more clear. Wouldn't be possible to replace the definition above for class-head for the following?


  class-key attribute-specifier-seqopt class-head-nameopt class-virt-specifieropt base-clauseopt


No. If you did, then there would be ambiguity. class final could mean a named class called final or an unnamed class that uses final as the virtual specifier.

Because of how the grammar is defined, class final always means a class named final. The grammar is unambiguous. The bracketed notation is not normative text; it simply explains the reason for the two definitions.

Now, you could define the grammar a different way to achieve the same effect, by adding another term:


  class-key attribute-specifier-seqopt class-head-name-stuffopt base-clauseopt


  class-head-name class-virt-specifieropt