4

Conceptually the following does not breach privacy in my opinion. But it is forbidden.

struct A
{
        int a;
        int b;
        int c;
};
struct B
{
        int a;
        int b;
private:
        int c;
};

int main (int argc, char * argv[])
{
        auto a = A{1,2,3}; //ok
        auto b = A{1,2};   //ok
        auto c = B{1,2,3}; //error
        auto d = B{1,2};   //error
        return 0;
}

Adding a manual constructor would allow brace initialization for the private members. But the beauty of aggregates and pods is the little amount of coding you need, hence this is annoying.

On the other hand, this is a privacy breach in my opinion but this is allowed by the standard.

Patrick Fromberg
  • 1,313
  • 11
  • 37
  • 3
    You can't use aggregate initialization for `struct B` because it's not an aggregate (all non-static members of an aggregate must be public). – Jerry Coffin Jan 25 '18 at 02:17
  • @Jerry, yes I know, this is what I am saying. But I am also complaining about it. Why on earth does the standard make things complicated that could be so easy? – Patrick Fromberg Jan 25 '18 at 02:20
  • 1
    You're basically asking why non-members of the class can't write private variables. This is by design. The linked question is a corner case, arguably a standard defect. – GManNickG Jan 25 '18 at 02:26
  • 1
    @GMan. Why consider brace initialization as a non-member access? To me it's something vaguely similar to a constructor call. It's a new kind of automatic constructor. – Patrick Fromberg Jan 25 '18 at 02:34
  • 1
    The current rules are simple and straightforward. If you allowed aggregate initialization of something with private members, what would you do with something like `class A { int a; public: int b; }; A a{1};` Do you use the `1` to initialize `A::a` or `A::b`? Either choice is going to leave a fair number of people upset and/or confused. – Jerry Coffin Jan 25 '18 at 02:34

1 Answers1

7

There is no such thing as an aggregate with private or protected non-static data members. All non-static data members of an aggregate must be public.

private:
    int c;

causes B to no longer be an aggregate. Thus aggregate initialization cannot work anymore.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182