0
class myClass {
    const std::vector<int> myVec = {1,1}; //works
    //const std::vector<int> myVec (2,1); //doesn't work
}

I'm trying to define a constant vector in a class.

Why the first line works while the second line doesn't?

The error is

g++ test.C
test.C:6:35: error: expected identifier before numeric constant
     const std::vector<int> myVec (2,1);
                                   ^
test.C:6:35: error: expected ',' or '...' before numeric constant
Godly Wolf
  • 13
  • 2
  • 1
    Non-static data members can be initialized with [member initializer list](https://en.cppreference.com/w/cpp/language/initializer_list) or with a [default member initializer](https://en.cppreference.com/w/cpp/language/data_members#Member_initialization). – 273K Jun 19 '22 at 15:28

1 Answers1

1
const std::vector<int> myVec (2,1);

starts to define a function named myVec returning a const std::vector<int> but then instead of naming the types of the arguments you have integer literals.

Did you mean

const std::vector<int> myVec {2,1};

or

const std::vector<int> myVec = std::vector<int>(2, 1);
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
  • Note that "`(` starts to define a function" only applies at class scope. – HolyBlackCat Jun 19 '22 at 15:33
  • Dear Goswin, thank you so much for your prompt reply I meant the latter, to declare and assign a variable in one go The syntax of `const std::vector myVec (2,1);` works well standing alone, but not working inside a class – Godly Wolf Jun 19 '22 at 15:37