Sami1202
Sami1202

Reputation: 127

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

Upvotes: 1

Views: 6124

Answers (2)

Michal
Michal

Reputation: 148

What might seem confusing is the fact that std::bitset does not explicitly define operator=. Compiler will, however, generate one (see this question). You can actually check that using cppinsight. This means that, in combination with the implicit constructor mentioned in the accepted answer, your code works. You can see the constructor call and subsequent assignment in the cppinsight example.

Upvotes: 1

Axalo
Axalo

Reputation: 2953

Bitset's non-string constructors are implicit.

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

b = bitset<8>(145);

Upvotes: 5

Related Questions