Search code examples
c++c++11bitset

Assign a value to Bitset


I'm curious to know why the following code is working! According to bitset template class, you can assign a value to bitset (int or binary representation as string) by constructor but not after that. But here you can see that explicit assign of a integer works fine.

#include <iostream>
#include <bitset>
#include <string>
using namespace std;

int main()
{
    bitset<8> b(string("101"));
    cout << b.to_ullong()<<"\n";
    b= 145;
    cout << b<<"\n";
    return 0;
}

this question also might be relevant. How to assign bitset value from a string after initializaion


Solution

  • Bitset's non-string constructors are implicit.

    If they were declared as explicit you would indeed have to write

    b = bitset<8>(145);