2

I have the following class as a wrapper around the basic type bool:

class MyBoolean {
public:
    MyBoolean(bool value = false):value(value) {};
    virtual ~MyBoolean() {};

    void MySpecialFunction();
    ...

private:
    bool value;
}

I want to use MyBoolean in expressions as normal bool. That is, assign to it, compare, etc. For that I define the assignment and implicit type cast operators.

inline operator bool() const {
    return value;
}
inline bool operator = (const bool &rhs) {
    return value = rhs;
}

It seems however that the assignment operator is not needed. The following code compiles just with type cast operator, without the assignment operator:

MyBoolean b;
b = true;

Why doesn't the compiler complain it cannot assign bool into MyBoolean? What is the default implementation of the assignment operator from a different type in C++?

anc
  • 191
  • 1
  • 19
Brain
  • 311
  • 2
  • 12
  • Smart compilers. – DimChtz Jul 31 '17 at 13:30
  • 1
    Possible duplicate of [What is a converting constructor in C++ ? What is it for?](https://stackoverflow.com/questions/15077466/what-is-a-converting-constructor-in-c-what-is-it-for) – LogicStuff Jul 31 '17 at 13:32
  • Thanks a lot, that explains it! A related question then: what is the most efficient implementation, i.e. adding the least overhead. Shall I overload all the necessary operators (=, ==, !=, !, &&, ||)? Or is this minimalistic approach good enough? – Brain Jul 31 '17 at 13:43
  • 1
    @DimChtz No, not "smart compilers" but "language rules" (in this case). – Jesper Juhl Jul 31 '17 at 13:49

3 Answers3

3

You constructor MyBoolean(bool value = false) is a "converting constructor" and the compiler is allowed to use such a one to generate one implicit conversion (in this case from bool to MyBoolean).

If you do not want the constructor to be used for implicit conversions then declare it as explicit - as in

explicit MyBoolean(bool value = false)
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
2

The reason you do not need the assignment operator is because you have a non-explicit converting constructor. When you do

b = true;

The compiler sees that it can convert true to a MyBoolean using

MyBoolean(bool value = false):value(value) {};

Since you get one user provided conversion the compiler constructs a temporary MyBoolean and then assigns that to b using the default copy assignment operator.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Does the converting constructor create more overhead than if the assignment operator is defined and used? – Brain Jul 31 '17 at 14:00
  • @Brain Yes, you construct a temporary. If you had a assignment operator that took a `bool` no temporary would need to be created. – NathanOliver Jul 31 '17 at 14:01
0

When you do b = true it makes a new MyBoolean.

MyBoolean b;
b = true;

Evaluates to

MyBoolean b;
b = MyBoolean(true);

This is called implicit type conversion

N00byEdge
  • 1,106
  • 7
  • 18