This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 14.1.1 - Non-static data members should be either all private or all public
Category: Advisory
Analysis: Decidable,Single Translation Unit
Rationale
By implementing a class interface with member functions only and making all the class data members inaccessible, it is possible to retain more
control over how the object’s state can be modified. For example, enforcing an invariant for the class, or making sure that the address of a data
member of a class can not be accessed by its users, making detection of possibly dangling addresses more robust.
However, some classes merely need to group together some data members without defining any invariants. For such classes, making the data members
public simplifies the code (less code to maintain, easy use of structured bindings), therefore reducing the risk of errors.
These two situations are usually exclusive, with it being difficult to reason about a class that has both public and
private data members.
The use of protected data members would mean that:
- The members should not be directly accessed; and
- The members can be directly accessed by any derived class, possibly breaking the invariants established by the base class.
If derived classes require privileged access to data members, those members should be private and protected functions
should be defined to allow them to be manipulated.
Example
class C1 // Non-compliant - has public and private members
{
public:
int32_t a;
private:
int32_t b;
};
struct C2 // Compliant
{
C2( int32_t a, int32_t b ) : a{ a }, b{ b } {}
int32_t a;
int32_t b;
};
class C3 // Compliant - rule does not apply to static members
{
public:
C3( int32_t a, int32_t b ) : a{ a }, b{ b } {}
static int32_t s;
private:
int32_t a;
int32_t b;
};
Copyright The MISRA Consortium Limited © 2023