Why does C ++ have both classes and structures?

Possible duplicate:
What are the differences between structure and class in C ++

If the difference between structures and classes is the default access specifier (in C ++), then why does C ++ also have classes?

+4
source share
4 answers

Firstly, it is backward compatible with C. Secondly (and, more importantly), it helps describe your intentions. The standard convention is that PODs should be denoted with a struct , and collections of data and behavior should be denoted with a class .

+12
source

You want classes that have a default access specifier to be private when designing object-oriented hierarchies, but structures need the default access specifier to be publicly available to maintain compatibility with C.

+1
source

Like everyone else, the main difference is the default protection level (i.e., open or closed). However, this is also a good sign of the actual use of the data structure. For example, sometimes you may need a lightweight structure similar to a java bean. In this case, you can simply:

 struct point { float x, y; }; 

It is clear that you are not using any C ++ features here, compared to:

 class point { public: float x, y; }; 

It is less clear what your intention is. Probably the second example I would call bad code, because someone did not provide recipients and setters.

0
source

Backward compatibility with C. C did not have classes, but it did have structures.

Please note that this is “backward compatible” only in the text of the .c file. In C ++, structures are really classes with the default public exposure instead of the standard private exposure.

 class Bob { // I haven't overridden the exposure, so it private int age; int height; public: Bob(); }; struct Bob { // I haven't overridden the exposure, so it public int age; int height; // note the constructor defaults to the "default" constructor. }; 

The true structure of style C is defined as

 extern "C" { struct Bob { int age; int height; }; } 

In this case, the age becomes more than the alias "offset +0", and the height becomes more like the alias "offset + (sizeof (int) + alignment with the border of the memory manager) instead of conceptual fields that can be implemented in any way desired.

-1
source

All Articles