0

I have two questions. I run the below code and it sets each array object variable to 20 ın GCC 6.3 version. However, when I try the higher version of GCC, It gives an error. Why is there this changing?

#include <iostream>
class A{
    int a;
    public:
    A(int);
};

A::A(int init_val){
    this -> a = init_val;
}

int main(){
    A a[10](20);
}

Actually, I want to set an array which has more parameters for a constructor like that:

A(int, char);
A a[10](20, 'A');

The final version of the code is below. This gives an error in every version of gcc.

Is there any way to set an array object like that?

#include <iostream>
class A{
    int a;
    char b;
    public:
    A(int, char);
};

A::A(int init_val, char init_ch ){
    this -> a = init_val;
    this -> b = init_ch;
}

int main(){
    A a[10](20, 'A');
}
Selcuk
  • 109
  • 2
  • 11

2 Answers2

4

No, there is no way to initialise an array like that in C++. Neither of your attempts are well-formed.

You can initialise every element explicitly like this:

A a[10]{
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
    {20, 'A'},
};

If the element type were default constructible (which your class is not) and copy assignable (which your class is), then you could work around the inability by default initialising, and assigning the elements later. For example:

A a[10];
std::fill_n(a, std::size(a), A{20, 'A'});
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Without default ctor, that is correct. If you can add one, you could use `std::fill_n(a, 10, A{20, 'A'});` for a somewhat nicer syntax. See also [here](https://stackoverflow.com/questions/1065774/initialization-of-all-elements-of-an-array-to-one-default-value-in-c) – Cedric Nov 26 '20 at 12:42
0

If the initializers are actual compile time constant values, you can just add a default ctor:

class A {
    ...
    A(): a(20) {}
}

But I know no clean way in the general case.There is a possible workaround if you can use dynamic objects: use a vector and emplace_back the objects. At the end, the vector will contain an array of objects:

va = std::vector<A>;
va.reserve(10)
for (i=0; i<10; i++) {
   va.emplace_back(20, 'a');
}
A *a = va.data();              // you now have a array of 10 A objects

You simply have to make the backing vector last as long as you need the array to exist...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252