Person.Junkie
Person.Junkie

Reputation: 1886

C++ conversion operator overload

'int' and 'double' conversion functions is 'explicit' and in this code why have I permit for use this conversion instead of error message? If I delete all my conversion overload functions code occur 'conversion error'

class Person
{
public:
    Person(string s = "", int age = 0) :Name(s), Age(age) {}
    operator string() const { return Name; }
    explicit operator int() const{ return 10; }  // ! Explicit
    explicit operator double()const { return 20; } //! Explicit
    operator bool()const { if (Name != "") return true; return false; } // using this
};

int main(){

    Person a;
    int z = a;
    std::cout << z << std::endl;   // Why print "1"?  Why uses bool conversion?
}

I this it is answer:

Because 'a' can not be convert to int or double it occur error, but because it has bool conversion function, which can convert to int and int to double, code use this function.

Upvotes: 1

Views: 238

Answers (1)

Deduplicator
Deduplicator

Reputation: 45654

int z = a;

Looks innocuous, right?

Well, the above line calls the implicit bool-conversion-operator, because that's the only way you left it to get from Person to int, and that only needs one user-defined conversion (the maximum allowed).

This is the reason for the safe-bool-idiom before C++11, and the major reason for the general advice to mark conversion operators and single-argument ctors explicit unless they are not transformative nor lossy.

If you want to see it for yourself, fix your code and trace invocation of your operator bool.

Upvotes: 1

Related Questions