Re: Defaulted initializer constructor

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



n 26 November 2012 09:48, Henrik Mannerström wrote:
> Hello!
>
> If I write
> class MT {
> public:
> int k[3];
> };
>
> then g++(4.6.3) accepts
> MT a{{0,1,2}};
>
> but if I add a constructor
> MT() {
> for (int i = 0;i!=3;i++)
> k[i] = 0;
> }

This constructor could be written far more easily:

MT() : k() { }

This initializes every element of the array to zero, and stays correct
if you change the array size.

> then MT a{{0,1,2}}; gives me
> error: no matching function for call to ‘MT::MT(<brace-enclosed
> initializer list>)’
>
> Now, if I add
> MT(std::initializer_list<int> list) = default;
>
> I get
> error: ‘MT::MT(std::initializer_list<int>)’ cannot be defaulted
>
> What constructor was I (gcc) using earlier and how can I get i back?

It wasn't using a constructor, you were using aggregate initialization
to provide initial values for each member. A class with a constructor
is not an aggregate, so cannot use aggregate initialization.  Adding a
constructor to your class implies the type is not a simple aggregate,
it needs a manually-written constructor with user-defined effects.

You could define a constructor that accepts arguments:

MT::MT(int i0=0, int i1=0, int i2=0)
: k{i0, i1, i2}
{ }

This constructor works for zero to three arguments, if you don't want
that then have two separate constructors taking zero arguments and
three arguments. Either way, you can do:

MT a{ 0, 1, 2 };
MT b;



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux