Pages

Monday, February 15, 2010

Difference between class and structure in C++

References:
1. http://www.cplusplus.com/doc/tutorial/classes/
2. http://scv.bu.edu/computation/bluegene/IBMdocs/compiler/xlc-8.0/html/language/ref/cplr054.htm
3. http://en.wikipedia.org/wiki/C%2B%2B_classes#Differences_between_struct_in_C_and_classes_in_C.2B.2B
4. http://msdn.microsoft.com/en-us/library/6w96b5h7(VS.80).aspx

Quotation from the first link (C++):
Classes can be defined not only with keyword class, but also with keywords struct and union.

The concepts of class and data structure are so similar that both keywords (struct and class) can be used in C++ to declare classes (i.e. structs can also have function members in C++, not only data members). The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access. For all other purposes both keywords are equivalent.

The concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold function members. The default access in union classes is public.

So the difference is only the public access by default for the structures. Probably, Straustrup made it by intention - the reason is the compatability between C and C++. Of course, this compatability will be lost, if virtual methods will be added to the structure declaration.

No comments:

Post a Comment