Files
cppdraft_translate/cppdraft/class/name.md
2025-10-25 03:02:53 +03:00

4.8 KiB

[class.name]

11 Classes [class]

11.3 Class names [class.name]

1

#

A class definition introduces a new type.

[Example 1:

struct X { int a; };struct Y { int a; }; X a1; Y a2;int a3; declares three variables of three different types.

This implies thata1 = a2; // error: Y assigned to X a1 = a3; // error: int assigned to X are type mismatches, and thatint f(X);int f(Y);declare overloads ([over]) named f and not simply a single function f twice.

For the same reason,struct S { int a; };struct S { int a; }; // error: double definition is ill-formed because it defines S twice.

— end example]

2

#

[Note 1:

It can be necessary to use an elaborated-type-specifier to refer to a class that belongs to a scope in which its name is also bound to a variable, function, or enumerator ([basic.lookup.elab]).

[Example 2: struct stat {// ...};

stat gstat; // use plain stat to define variableint stat(struct stat*); // stat now also names a functionvoid f() {struct stat* ps; // struct prefix needed to name struct stat stat(ps); // call stat function} — end example]

An elaborated-type-specifier can also be used to declare an identifier as a class-name.

[Example 3: struct s { int a; };

void g() {struct s; // hide global struct s with a block-scope declaration s* p; // refer to local struct sstruct s { char* p; }; // define local struct sstruct s; // redeclaration, has no effect} — end example]

Such declarations allow definition of classes that refer to each other.

[Example 4: class Vector;

class Matrix {// ...friend Vector operator*(const Matrix&, const Vector&);};

class Vector {// ...friend Vector operator*(const Matrix&, const Vector&);};

Declaration of friends is described in [class.friend], operator functions in [over.oper].

— end example]

— end note]

3

#

[Note 2:

An elaborated-type-specifier ([dcl.type.elab]) can also be used as a type-specifier as part of a declaration.

It differs from a class declaration in that it can refer to an existing class of the given name.

— end note]

[Example 5: struct s { int a; };

void g(int s) {struct s* p = new struct s; // global s p->a = s; // parameter s} — end example]

4

#

[Note 3:

The declaration of a class name takes effect immediately after theidentifier is seen in the class definition orelaborated-type-specifier.

[Example 6:

class A * A; first specifies A to be the name of a class and then redefines it as the name of a pointer to an object of that class.

This means that the elaborated form class A must be used to refer to the class.

Such artistry with names can be confusing and is best avoided.

— end example]

— end note]

5

#

A simple-template-id is only a class-name if its template-name names a class template.