Brain
Brain

Reputation: 321

C++ default assignment operator from different type

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++?

Upvotes: 2

Views: 1161

Answers (3)

Jesper Juhl
Jesper Juhl

Reputation: 31447

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)

Upvotes: 3

N00byEdge
N00byEdge

Reputation: 1136

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

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180415

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.

Upvotes: 2

Related Questions