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?

1

5 Answers 5

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++.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

0
C::init(){

   bK [0] = 3;
   bk [1] = 7;
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.