Why am I getting an error when I try this in Visual C++?
struct S { };
typedef S *S;
Doesn't C++ let you typedef
a name that was previously only declared as a class
or struct
?
Or am I misunderstanding what's going on?
Why am I getting an error when I try this in Visual C++?
struct S { };
typedef S *S;
Doesn't C++ let you typedef
a name that was previously only declared as a class
or struct
?
Or am I misunderstanding what's going on?
C++ does allow you to typedef an existing class name, but only in a very restricted way. Once you declared your struct S
you can do
typedef struct S S;
but you cannot do
typedef struct S *S; // ERROR
or
typedef int S; // ERROR
In the first case the fact that you are redefining S
as a pointer is what breaks it.
The language specification says in 7.1.3/2
In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.
"Already refers" is the key part. In simple words, you can redefine a class name to stand for the same class type, but not for a pointer to the class type or anything else.
The aforementioned part of C++ standard is also what allows you to write repetitive typedefs like
typedef int T;
typedef int T;
typedef int T;
which would be illegal in C.
This would be okay in C because struct names do not clash with type names - the struct name would be struct S
and the type name would be just S
. However, in C++ all names are considered to come from the same pool of names, so the two names in your example will clash.
You are trying to define S (the typedef) which clashes with "S" (the struct name).