2

I'm going through someone else's code and came across the following syntax:

typedef struct abc {

   abc() : member(0){}

   unsigned int member

}

It seems like a class with member variable and a constructor, except it is declared struct. I have two questions here.

  1. Is this syntax supported in C?
  2. What would be a reason to use structs over classes?

Thanks a lot in advance.

PS: how do I format the code?

Puppy
  • 144,682
  • 38
  • 256
  • 465
dustin ledezma
  • 615
  • 2
  • 6
  • 10
  • I formatted the code for you by indenting 4 spaces. You can highlight the code and press the `{}` icon above the editing field. You need to leave a blank line before and after the code. Similar thing goes for the numbered list. – Ted Hopp Jun 05 '11 at 17:06
  • see also http://stackoverflow.com/questions/2750270/c-c-struct-vs-class – Cubbi Jun 05 '11 at 17:07

6 Answers6

8

This is not valid C.

In C++, struct and class are essentially synonyms. The only difference is that members and inheritance are public by default in a struct, and private by default in a class.

There are no hard guidelines on whether to choose struct or class. However, you'll often find people using struct only for simple C-like plain old data structures ("PODs").

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

This is most assuredly just C++. struct and class are identical in C++, except for defaulting to public instead of private for inheritance and class contents.

Puppy
  • 144,682
  • 38
  • 256
  • 465
0

In C++, struct and class are essentially the same thing, except that for a struct members are public by default. So just read it as you would a class.

Codie CodeMonkey
  • 7,669
  • 2
  • 29
  • 45
0

abc() is a constructor of class abc, member is a internal variable, constructor abc defaults set member as 0.

wuxb
  • 2,572
  • 1
  • 21
  • 30
0
  1. The syntax is supported. The constructor initializes member to 0 and does nothing else.
  2. struct has a default access of public.
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

This is C++ code, however using typedef struct (that comes from C) in C++ code is awful. There is difference between C and C++ and in C++ you don't need to typedef structs. struct MyStruct is sufficient declaration if you want to refer your struct via MyStruct myStruct;. Mixing C with C++ is bad.

shjeff
  • 405
  • 4
  • 17