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:
- If you don't specify
public:
orprivate:
, 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.
You might consider this for guidelines on when to go for struct or class, https://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx .
Member of a class defined with the keyword
class
areprivate
by default. Members of a class defined with the keywordsstruct
(orunion
) arepublic
by default.In absence of an access-specifier for a base class,
public
is assumed when the derived class is declaredstruct
andprivate
is assumed when the class is declaredclass
.You can declare an
enum class
but not anenum struct
.You can use
template<class T>
but nottemplate<struct T>
.Note also that the C++ standard allows you to forward-declare a type as a
struct
, and then useclass
when declaring the type and vice-versa. Also,std::is_class<Y>::value
istrue
for Y being astruct
and aclass
, but isfalse
for anenum class
.According to Stroustrup in the C++ Programming Language:
Functionally, there is no difference other than the public / private
Here is a good explanation: http://carcino.gen.nz/tech/cpp/struct_vs_class.php
The main difference between struct and class is that in struct you can only declare data variables of different data types while in class you can declare data variables,member functions and thus you can manipulate data variables through functions.
-> another handy thing that i find in class vs struct is that while implementing files in a program if you want to make some operations of a struct again and again on every new set of operations you need to make a separate function and you need to pass object of struct after reading it from the file so as to make some operations on it . while in class if you make a function that does some operations on the data needed everytime..its easy you just have to read object from file and call the function..
But it depennds on the programmer which way he/she finds suitable...according to me i prefer class everytime just because it supports OOPs and thats the reason it is implemented in almost every languages and its the wonderful feature of all time programming ;-)
And yeah the most unforgotten difference i forgot to mention is that class supports data hiding and also supports operations that are performed on built in data types while struct doesnt !