0
#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{   
   private:
   int array[]={0,2,4,6,8,10,12};//this line is the root cause of the error but why ?   
   public :
   void compute();
};
void Test::compute()
{
    int result =0;
    for(int i=0;i<7;i++)
    {
        result += array[i];
    }
        cout<<result;
}
int main()
{
    Test obj;
    obj.compute();
    return 0;
}

If I replace int array[] in the above code with array[7] then the program compiles and runs with warnings.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Vineet Tambe
  • 93
  • 2
  • 7
  • [I believe this has already been answered here.](https://stackoverflow.com/questions/21152171/too-many-initializers-for-int-0-c) – Jayesh Khullar Mar 07 '19 at 14:48

1 Answers1

5

Unlike an array in any other scope, an array in a class cannot be sized by it's initializer. The initializer is just syntactic sugar telling the compiler what to use to initialize the member. That means what you really have is

class Test
{   
   private:
   int array[]; 
   public :
   void compute();
   Test(): array({0,2,4,6,8,10,12}) {}
};

which can't work as there is no size information for the array.

It works when you specify a size, because now there is actually a valid size. If you want to be able to have something like

int array[]={0,2,4,6,8,10,12};

in the class then use a std::vector instead like

std::vector<int> array={0,2,4,6,8,10,12};
BiagioF
  • 9,368
  • 2
  • 26
  • 50
NathanOliver
  • 171,901
  • 28
  • 288
  • 402