Why do we need the private specifier in C ++, if by default so all functions and variables are private?

    2 answers 2

    For example, because in the default structure all functions and fields are open .

    In addition, the textual order of the fields affects the order in which they are initialized in the constructor ! Therefore, it is impossible to just rearrange the class fields; this may change the meaning of the program.

    Example. Suppose we want the len field to be open and the data field to be closed.

     class MyString { public: unsigned len; private: char* data; public: MyString(const char* s) : len(std::strlen(s)), data(new char[len + 1]) { std::memcpy(data, s, len + 1); } // ... }; 

    We cannot rearrange len and data , because initializers in the constructor are executed in the order in which the fields are specified, and not in the order in which they are written in the code! So, without private not enough.

      No, of course, you can first describe the closed members and private functions in the class, and only then the open members ... And never use the struct if you need at least one private member ...

      But, frankly, how inconvenient it is - when changing access, you need to move the member in the class, the interface should always be shown only after the internals of the class ...

      No, perhaps, nevertheless, the convenience of memorizing one keyword less is not able to outweigh all the advantages provided by this keyword, no? :)