1

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

Community
  • 1
  • 1
Sami1202
  • 127
  • 1
  • 8

2 Answers2

5

Bitset's non-string constructors are implicit.

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

b = bitset<8>(145);
Axalo
  • 2,953
  • 4
  • 25
  • 39
  • you mean that 145 is a constructor in above? I suppose that here = operator must have been overloaded and this is not a constructor call. but I can not see any overload for = in your reference – Sami1202 Jan 24 '15 at 01:46
  • @Sami1202 no. I meant that 145 is automatically converted into a bitset<8>. That has nothing to do with the assignment operator. – Axalo Jan 24 '15 at 01:48
1

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.

Michal
  • 148
  • 2
  • 6