0

I'm trying to create a variable of type std::bitset<16> in my class:

#include <bitset>

class foo{
public:
    std::bitset<16> bar (0xfa2);
};

But the program fails to compile with the following error:

$ g++ src/test.h 
src/test.h:5:26: error: expected identifier before numeric constant
    5 |     std::bitset<16> bar (0xfa2);
      |                          ^~~~~
src/test.h:5:26: error: expected ‘,’ or ‘...’ before numeric constant

I don't know what I'm doing wrong. The bitset definition is copied straight from the documentation example so I don't think it should throw any error. I've been trying to fix this for a while, but only noticed that the program compiles if I initialize the bitset without any argument, which is not what I'm trying to do anyways.

Jan
  • 25
  • 6
  • It looks like your compiler is parsing `bar` as a function returning `std::bitset<16>` instead of a variable. Change `std::bitset<16> bar (0xfa2);` to `std::bitset<16> bar {0xfa2};` – drescherjm Feb 19 '22 at 17:48
  • `The bitset definition is copied straight from the documentation` No, it is not copied straight. The context is different. You should learn initialization of class members. – 273K Feb 19 '22 at 17:50
  • @drescherjm You're right. That's it. If you want, you can turn your comment into an answer so I can accept it. – Jan Feb 19 '22 at 17:54
  • I think this is an instance of the [most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse). There is an entire [tag](https://stackoverflow.com/questions/tagged/most-vexing-parse) about it. – Nate Eldredge Feb 19 '22 at 17:55
  • There are duplicates for vexing parse which we could close this with. However with that said if you don't know about vexing parse you are highly unlikely to find the duplicate via a search. – drescherjm Feb 19 '22 at 17:57
  • @NateEldredge It's not the most vexing parse; that declaration cannot be parsed as a function declaration. It's just that a [*default member initializer*](https://en.cppreference.com/w/cpp/language/data_members#Member_initialization) must use brace-or-equals initializer, and can't use parentheses. – Igor Tandetnik Feb 19 '22 at 20:35

0 Answers0