Possible Duplicate:
What are the differences between struct and class in C++
I've done my homework and had diverse answers on Google.
Some say structs do not have inheritance, some say structs do not have access specifiers, while others say they have both.
Could someone clarify then, the differences between a struct and a class in C and C++, and also the difference between a struct in C & C++.
In C++, the only difference between a struct and a class is that struct members are public by default, and class members are private by default.
However, as a matter of style, it's best to use the struct
keyword for something that could reasonably be a struct in C (more or less POD types), and the class
keyword if it uses C++-specific features such as inheritance and member functions.
C does not have classes.
C structs cannot use C++-specific features.
EDIT:
The C++ FAQ Lite, question 7.9, has this to say:
The members and base classes of a
struct
arepublic
by default, while inclass
, they default toprivate
. Note: you should make your base classes explicitlypublic
,private
, orprotected
, rather than relying on the defaults.
struct
andclass
are otherwise functionally equivalent.OK, enough of that squeaky clean techno talk. Emotionally, most developers make a strong distinction between a
class
and astruct
. Astruct
simply feels like an open pile of bits with very little in the way of encapsulation or functionality. Aclass
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 thestruct
keyword if you have a class that has very few methods and haspublic
data (such things do exist in well designed systems!), but otherwise you should probably use theclass
keyword.
And quoting Stroustrup's "The C++ Programming Language", 4th edition, section 16.2.4:
These two definitions of S are interchangeable, though it is usually wise to stick to one style. Which style you use depends on circumstances and taste. I tend to use struct for classes that I think of as "just simple data structures." If I think of a class as "a proper type with an invariant," I use class. Constructors and access functions can be quite useful even for *struct*s, but as a shorthand rather than guarantors of invariants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With