This question was already asked in the context of C#/.Net.
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
I'll start with an obvious difference:
public:
or private:
, members of a struct are public by default; members of a class are private by default.I'm sure there are other differences to be found in the obscure corners of the C++ specification.
Structure vs ClassA structure is a value type so it is stored on the stack, but a class is a reference type and is stored on the heap. A structure doesn't support inheritance, and polymorphism, but a class supports both. By default, all the struct members are public but class members are by default private in nature.
Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.
You forget the tricky 2nd difference between classes and structs.
Quoth the standard (§11.2.2 in C++98 through C++11):
In absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.
And just for completeness' sake, the more widely known difference between class and struct is defined in (11.2):
Member of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.
Additional difference: the keyword class
can be used to declare template parameters, while the struct
keyword cannot be so used.
Quoting The C++ FAQ,
[7.8] What's the difference between the keywords struct and class?
The members and base classes of a struct are public 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.
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