Rule 11-0-1 and POD types

Moderators: david ward, misra cpp

Post Reply
cgpzs
Posts: 1
Joined: Wed Mar 24, 2021 11:52 am
Company: Zenseact AB

Rule 11-0-1 and POD types

Post by cgpzs » Wed Mar 24, 2021 1:57 pm

Hi,

I have a few questions about rule M11-0-1:

Rule 11–0–1
(Required)
Member data in non-POD class types shall be private.

* As posted in a previous question, "class types" here means "class, struct or union". Is my understanding correct?
* Why should the fact that a type is POD or not influence access control?

Let's have the following controversial example. Having the following POD type:

Code: Select all

struct Foo
{  
   int x;
   int y;
};
The design for this struct is to aggregate 2 variables together, but there's no invariance to hold. x and y can vary independently. The struct is POD, so it's compliant with M11-0-1.

Now, in the future we want to extend `Foo` with another variable independent from x and y:

Code: Select all

struct Foo
{
    int x;
    int y;
    std::string name;
};
Now, since `Foo` contains a `std::string`, and `std::string` is not a POD, then `Foo` becomes a non-POD. In turn, this now violates M11-0-1, which forces us to make these fields private. This leads to adding trivial boilerplate getters and setters to `Foo`, and every consumer of this struct needs to change their way of interacting with `Foo`.

This wouldn't happen if `name` was a `char const*`:

Code: Select all

struct Foo
{
    int x;
    int y;
    char const* name;
};
The semantics of `Foo` are identical to before, just using a different type for one of its members. Why should that lead to such dramatic changes?

A similar example:

Code: Select all

struct Bar
{
    std::vector<int> points_x;
    std::vector<int> points_y;
};
`Bar` is a collection of points that are independent from each other; there's no invariant.

Besides, POD types are types that are "compatible with the types used in the C programming language". Why should this be a concern if we are programming in C++? Why should we make our structs "C-compatible", if they are meant to be used in C++ code?

misra cpp
Posts: 161
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Rule 11-0-1 and POD types

Post by misra cpp » Fri Jun 04, 2021 3:22 pm

Your interpretation of the current rule is correct:
* struct with 2 ints - compliant
* struct with 2 ints and a std::string - non-compliant
* struct with 2 ints and a const char * - compliant
* struct with 2 vectors - non-compiant

We understand your concerns and this rule is under review for the next version
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.11 Member access control (C++)”