tags:

views:

244

answers:

4

Could anybody please tell me what is the main difference between C & C++ structures.

+3  A: 

C++ structures behave like C++ classes, allowing methods, contructors, destructors... The main diffrent between classes and C++ structures is that structures by default are everything inside public, while classes by default everything inside is private (ie: nothing outside can access them directly)

speeder
According to my CS prof, another difference between structs and classes is "you can't fail a struct"
Jeremy Friesner
A: 

C structs is more akin to a definition of a composite data structure

C++ structs can be thought of as a class but scope of all member variables are defaulted to public.

Anthony Kong
+6  A: 

In C++ struct and class are the exact same thing, except for that struct defaults to public visibility and class defaults to private visiblity.

In C, struct names are in their own namespace, so if you have struct Foo {};, you need to write struct Foo foo; to create a variable of that type, while in C++ you can write just Foo foo;, albeit the C style is also permitted. C programmers usually use typedef struct {} Foo; to allow the C++ syntax for variable definitions.

The C programming language also does not support visibility restrictions, member functions or inheritance.

Tronic
In C++ struct names are also in their own name space. The difference is that when searching for an identifier the compiler will first look in the general name space, and if not found will also check the user-defined-classes name space. In c++ his is correct: `struct x {}; void x() {}` while this is not `typedef struct x {} x; void x() {}`, as the global identifier space already has an `x` (typedef) the declaration of the function will collide (BTW, in the first example, to create a variable you need to write `struct x var` so that the identifier is only searched for as a user defined type).
David Rodríguez - dribeas
A: 

In addition to the answers above, remember that C++ structures support inheritance and so can contain pointers to vtables. This can make a big difference when serializing and deserializing these structures across processes. Templates are supported too.

Vulcan Eager
Rather than mentioning vtables (which are not in the C++ language specification) you should mention `virtual` methods.
Thomas Matthews
The best process for serializing and deserializing structures is to have functionality that accesses the data fields (members) individually. Applies to both C and C++ languages. One primary reason is that the compiler is allowed to add padding between members (applies to both languages).
Thomas Matthews
In C, padding is only a matter of a few unused bytes when the data in serialized and deserialized in it's binary representation. With C++, it can create problems when using objects of classes with virtual functions.
Vulcan Eager