11.1 Access specifiers

11.1.1 Declare all data members private

If direct access to the object state is allowed through public or protected member data, encapsulation is reduced making the code harder to maintain. By implementing a class interface with member functions only, precise control is achieved over modifications to object state as well as allowing for pre and post conditions to be checked when accessing data.

#include <string>
#include <cassert>
               
class C
{
public:
C ();
                 
std::string m_id; // @@- Non-Compliant -@@
};

class D
{
public:
D ();
                 
std::string const & getId () const
{
assert (! m_id.empty () && "Id not yet specified");
return m_id;
}
                 
private:
std::string m_id; // @@+ Compliant +@@
};

Exception

Class types declared with the class key struct in an extern “C” block are intended to be compatible with C, and therefore such definitions are not covered by this rule.

For Example:

extern "C"
{
struct S // Compliant
{
int i;
int j;
};
}

References

  • HIC++ v3.3 – 3.4.1

Click here for references