2

so I have this class in the header

class C{

   int b [2];

   init();

}

and in C.cpp I have

C::init(){

   bK [2] = {3,7};
}

whereby I try to initialize the class variable b which is an array

but then the compiler returns the error expected ; before { token and expected primary expression before { token

what did i do wrong and how do I properly initialize array class variables?

kamikaze_pilot
  • 14,304
  • 35
  • 111
  • 171
  • How is this different than your other question? http://stackoverflow.com/questions/5732798/c-array-assignment-of-multiple-values –  Apr 20 '11 at 16:12

5 Answers5

4

End your class definition with a ;.

class C {

   int b [2];

   init();

};

Also, you cannot initialize an array like that away from the declaration in standard C++.

Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
1

You can't do this in pre-C++0x C++.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

That isn't allowed by the Standard (2003). Arrays declared in class cannot be initialized.

What you can do is this:

C::init(){
   b[0] = 3;
   b[1] = 7;
}

In C++0x, you can do this (if you choose to use std::vector):

class C
{
   std::vector<int> b;
   void init() 
   { 
       b = {3,7}; 
   }
};

See online demo : http://www.ideone.com/NN5aT

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0
C::init(){

   bK [0] = 3;
   bk [1] = 7;
}
Nick
  • 25,026
  • 7
  • 51
  • 83
0

You should declare you class members as either public, private or protected. And also you need a return type for you init(). You also might need a semicolon at the end of your class definition, which you can't do with c++ class members.

You should use a constructor instead of your init(). That way you don't have to call init() after every time you declare an object, it will be done for you.

class C{
private:
   int b[2];
public:
   C();

};

C::C()
{
    b[0] = 2;
    b[1] = 3;
}

Edit: After doing some testing, I found it was buggy. This code above has no errors in it. If you want to inline initialize a whole array, it has to be done in its declaration statement.

Nick Rolando
  • 25,879
  • 13
  • 79
  • 119