18

Why use a typedef class {} Name ?

I learnt this in IBM C++ doc, no hint to use here.

kiriloff
  • 25,609
  • 37
  • 148
  • 229

2 Answers2

33

This is a hangover from the 'C' language.

In C, if you have

struct Pt { int x; int y; };

then to declare a variable of this struct, you need to do

struct Pt p;

The typedef helped you avoid this in C

typedef struct { int x; int y; } Pt;

Now you can do

Pt p;

in C.

In C++, this was never necessary because

class Pt { int x; int y; };

allowed you to do

Pt p;

It provides no notational benefits in C++ as it does in C. OTOH, it leads to restrictions because this syntax does not provide any mechanism for construction, or destruction.

i.e. you cannot use the name typedef name in the constructor or destructor.

typedef class { int x; int y; } Pt;

You cannot have a constructor called Pt, nor a destructor. So in essence, most of the time, you shouldn't do this in C++.

user93353
  • 13,733
  • 8
  • 60
  • 122
3

This answer assumes that there's some interesting content in the class, not just {}.

In C++, you can have a function with the same name as a class (for compatibility with C), but you pretty much never want to.

You can't have a function with the same name as a typedef, so doing this protects you against ill-disciplined name choices. Pretty much nobody bothers, and even if you're going to bother you'd probably write it:

class Name {};
typedef Name Name; // reserve the name

If the code you're referring to really is as written (I can't see it by following your link), then it's rather like class Name {}; (which is a peculiar thing to write, why would you call an empty class Name?), but modified for the above consideration.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • I had no idea about this special treatment of typedef names. Grood to know! Also, I find it surprising and possibly disturbing that `typedef A A;` is allowed. – Agentlien Mar 19 '13 at 14:27
  • After playing around a bit with it, I can see that most compilers seem to implement it as described, but I can't find the relevant section in the standard. Do you think you could help with a reference? – Agentlien Mar 19 '13 at 14:32
  • @Agentlien: it's special treatment of class names rather than of typedefs. The relevant bit in C++11 is 3.3.10/2 ([basic.scope.hiding]). – Steve Jessop Mar 19 '13 at 15:00
  • So, if I understand this correctly (having read said section), the behavior stems from the fact that *only* `enum`s and `class`es can be hidden by function/data member/variable/enumerator declarations in the same scope. So, the `typedef` introduces a new name which *cannot* be hidden by a function (nor a variable, data member or enumerator). – Agentlien Mar 19 '13 at 15:26