Availability of private and protected in C++ structs

c, c++

Solution

C doesn't have C++style access modifiers. A C `struct` is just a composite object type containing members of other object types.

In C++, a `struct` and a `class` are almost identical; the only difference is that struct members are `public` by default, and class members are `private` by default. So this:

struct foo {
private:
    // ...
};

is equivalent to this:

class foo: {
    // ...
};

This has been answered elsewhere.

This implies that the `private`, `public`, and `protected` keywords are equally valid in either a `struct` definition or a `class` definition.

As a matter of programming style, on the other hand, if you're going to be using access modifiers, it's probably best to define your type as a `class` rather than as a `struct`. Opinions will differ on this, but IMHO the `struct` keyword should be used for POD (Plain Old Data) types, or for types that could be defined as `struct`s in C.

C++ structs, strictly speaking, are very different from C structs, and are nearly identical to C++ classes. But if I see something defined in C++ as a `struct`, I expect (or at least prefer) it to be something similar to a C `struct`.

Problem

Can we use access specifiers - `private` and `protected` - in C++ structs (as opposed to classes)? Also, do access modifiers exist in C?

Original source

Related problems