c++uniform-initializationlist-initialization

Why is C++ brace initialization not supported for aggregates with private members?


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.


Solution

  • 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.