Possible Duplicates:
When should you use a class vs a struct in C++?
What are the differences between struct and class in C++
struct X{
};
class X{
};
in C++, Same task can be done by class
as well as struct
. My question is where should I use class
and where struct
?
The differences between a struct and class in C++ are:
But basically anywhere you use a struct you could use a class, and vice versa, so it's really up to you what to use. Conventionally, when you have methods, it is more common to use a class, and when you only have data, structs are more commonly used.
I would say that if you want all the data members to be public, and you have no methods, then use a struct. Otherwise use a class. But that's just personal preference.
You've answered your own question in these words:
So use whatever makes you happy.
I usually use
struct
when I don't want to writepublic
explicitly, especially when I write template metaprogramming.Doesn't matter, both are equivalent. The only difference is that
struct
defaults to public member visibility and to public inheritance, andclass
to private ones.First a "Why is it like that?"
I should point out WHY structs are supported in C++.
Remember the point of C++ is twofold, first as an object oriented language, but ALSO as a "better C" with stronger type checking and a lot of other benefits. But, to remain backwards compatible (and, indeed to improve upon this backwards compatibility), structs were left in.
Also remember that the original C++ was cfront, which was essentially a pre-compiler for C. Anything that you could do in the original C++ you could do in C, it was just painful to do so and there were no guarantees without a mechanism to enforce the rules.
With that in mind let's look at the differences, once again.
Use struct when you want the members to be public BY DEFAULT (bad form, never assume defaults). But, also use a struct when you really want something that behaves like a C struct. It generally has very few methods if any and it generally has no operators. That's not a requirement of the language, it's just considered good form by many, if not most, C++ programmers. If you really want all of the functionality of a class, use a class.
A struct and a class are the same except for access (both in the declaration as well as in derived objects).
Example:
structs get there members public as default an classes get there members private as default.
Personnaly I use struct for very small containers.
I use generally classes with private members with getters & setters