Neha
Neha

Reputation: 821

private member array initialization through constructor initializer's list in c++

After going through all the questions asked about aggregate member initialization through initializer list still i am left with the question mark??? i have tried these two methods to initialize the private member array.

class C {
  C(const vector<int> &a): m_array(a) {} // using vector 
 private:
  C(initializer_list<int> a): m_array(a) {} //using initializer list
  int m_array[6];
};

both of the above methods throw error "cannot specify explicit initializer for arrays" in visual studio 2010. can somebody explain that whether these ways are correct, if yes then why these errors are coming up...

Upvotes: 1

Views: 910

Answers (2)

Abhinav
Abhinav

Reputation: 1490

When you say m_array(a). For this to be valid, m_array should be an object of some class say ArrayClass, which should have a parametrized constructor that accepts argument as you specified.

Now in your case, the m_array represents pointer to first element of the array m_array[]. Its quite simple to say that the constructors are called for objects and not for pointers. Writing m_array(a) means you want to do m_array = a, which is fundamentally wrong as array is allocated on stack and its base address can not be modified and you are trying to modify the array's base address.

What you can do is

  1. take a vector as member and that vector's constructor will take care of copying the elements.
  2. write your own array class.
  3. use a pointer (shallow copy)

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

Both these constructions require that arrays would have constructors with one parameter of type either std::vector<int> or std::initializer_list<int>. However arrays are aggregates. They have no constructor with parameter.

You should initialize the array in the bodies of the constructors.

One of approaches is to declare pointer to the first element of an array as the parameter and inside the body of the constructor to copy elements in the data member array.

For example

C( const int *a, size_t n )
{
   std::copy_n( a, std::min<size_t>( n, 6 ), array );
}

The other way is to use standard class std::array. For example

std::array<int, 6> array;

C( std::array<int, 6> ): array(a) {}

In the last case the constructor can be called as

C( { 1, 2, 3, 4, 5, 6 } );

.

Upvotes: 3

Related Questions