Is it only to allow logical grouping?
views:
189answers:
6It gives you flexibility. For example, you might have a bunch of constructors, some public, some protected, some private - wouldn't you want them all grouped together?
I think you are correct. Leaving it unforced allows users to group things as they see fit for better code readability.
The compiler may organize things differently in memory.
edit: as per the spec:
§9.2 clause 12 (1998 and 2003 standards):
Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
I found this information in a related SO question
My guess is that it is an outgrowth of the C philosophy, which assumes that you know what you are doing and gives you the maximum flexibility. It is like allowing a single = in an if statement.
I actually take advantage of this in a slightly unpleasant way: A code idiom I often use is a private member, with public accessor functions.
I have a MACRO (shudder) which automatically generates these from a single line.
example:
PROPERTY(int, MyVal);
...generates:...
private:
int fMyVal;
public:
void setMyVal(const int f) { fMyVal = f; };
int getMyVal() { return fMyVal; };
This works fine as long as you remember that the PROPERTY macro switches the current visiblity, which is not pleasant....
eg:
protected:
int v1;
PROPERTY (int, v2) // fv2 is private with public accessors
int v3; // whoops. f3 is public,
Why would you force it? It doesn't help the compiler out at all, it doesn't make things objectively easier for a person to read. Part of the C/C++ philosophy is that the language doesn't make arbitrary rules that don't enable some sort of feature/functionality.
It does make things MUCH easier for code generation. Many coding styles use access specifiers more than once per class - first defining all the local types, then all constructors, then all the methods, then all the instance variables, etc...
C++ gives you enough rope to shoot yourself in the foot, but it's that same flexibility that lets you build elegant, maintainable, and well abstracted applications.
In "The C++ Programming Language, 3rd edition," Stroustrup says this is to make code generation easier.
Although it does make sense that the position of each field in the actual binary is based on which order that field was declared in the source code, so this allows somebody to maintain some sort of layout compatibility with C or even other languages/specs.