Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does `bool operator = (bool b) const { return b; }` mean in C++?

I just learned about What is the meaning of "operator bool() const" , now I’m wondering what is the meaning of the second part of this definition?

struct always_false {
  operator bool() const { return false; }
  bool operator = (bool b) const { return b; }
  };

Specifically, what exactly is bool operator = (bool b) const { return b; } doing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

operator=() in a class foo allows you to define what it means to assign something to a foo object, ie:

 struct foo{
    int m_val;
    int operator=(int v){
      m_val = v;
   }
 }
 
 foo ff;
 ff = 42; // actually calls ff.operator=(42)

In your case, foo is in fact always_false, so you can do:

 always_false f;
 f = true; // ignored, and returns true
 f = false; // ignored and returns false

because there is an operator=(bool) defined for always_false.

However, it’s very odd and misleading to assign true since it’s supposed to always be false.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading