Initializer List on private members

Why does making m_i private make this fail to compile?
1
2
3
4
5
6
7
8
9
10
11
class Class
{
  public:
  int m_i;
};

int main( void )
{
  Class klass = { 1 };
  return 0;
}



The error would be:
error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘Class’
Last edited on
Only aggregates can be initialized with the brace syntax.

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).
Interesting, thanks.
> Only aggregates can be initialized with the brace syntax.

See: http://en.cppreference.com/w/cpp/language/list_initialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <complex>

class Class
{
    public: Class( int i = 0 ) : m_i(i) {} 
    private: int m_i;
};

Class foo( Class object, std::complex<double> c  ) { return { 23 } ; }

int main()
{
    Class klass = { 1 } ;
    Class klass2 { 56 } ;
    klass = foo( { 100 }, { 17, 4 } ) ;
    std::cout << "ok\n" ;
}

http://coliru.stacked-crooked.com/a/2f5361c638df0b97
Topic archived. No new replies allowed.