Sunday 3 February 2013


What's the difference between the keywords struct and class?

The members and base classes of a struct arepublic by default, while in class, they default to private. 

Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

OK, enough of that squeaky clean techno talk.Emotionally, most developers make a strong distinction between a class and a struct. A struct simply feels like an open pile of bits with very little in the way of encapsulation or functionality. A class feels like a living and responsible member of society with intelligent services, a strong encapsulation barrier, and a well defined interface. Since that's the connotation most people already have, you should probably use the struct keyword if you have a class that has very few methods and has public data (such things do exist in well designed systems!), but otherwise you should probably use the class keyword.

According to Stroustrup in the C++ Programming Language :

Which style you use depends on circumstances and taste. I usually prefer to use struct for classes that have all data public. 
I think of such classes as "not quite proper types, just data structures."
Functionally, there is no difference other thanthe public / private.
 ...if Stroustrup had changedthe semantics of struct so that its members where private by default, it would have broken compatibility (it is no longer as often true as the standards diverged, but all valid C programs were also valid C++ programs, which had a big effect on giving C++ a foothold).

So a new keyword, class was introduced to be exactly like a struct, but private by default.

 (C 03) says: "A "plain-old-data" POD-struct is an aggregate class that has no non-static data members of type non-POD-struct, non-POD-union (or array of such types) or reference, and has no user-defined copy assignment operator and no user-defined destructor." There is no restriction on using the "struct" class-key and no restriction on using "public"

No comments:

Post a Comment