2

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?

Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
  • This would be allowed in C, but not in C++. In C++, `struct S{...};` is roughly equivalent to `typedef struct S{...} S;` in C (i.e., afterwards, you can define an instance of `S` with just `S x;`, without requiring `struct S x;`. – Jerry Coffin Dec 02 '12 at 22:06

3 Answers3

5

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Ohh, so all it allows is a redundant declaration... interesting, thanks. +1 – user541686 Dec 02 '12 at 22:55
  • 1
    @Mehrdad Note that repeating the same typedef is allowed in C2011 by 6.7 (3): "a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type;" (with the exception of variably modified types). – Daniel Fischer Dec 02 '12 at 23:08
1

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.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

You are trying to define S (the typedef) which clashes with "S" (the struct name).

cxxl
  • 4,939
  • 3
  • 31
  • 52