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

Why does C++ implicit casting work, but explicitly casting throws an error (specific example)?

I was trying to overload the casting operator in C++ for practice, but I encountered a problem and I can’t figure out the issue. In the example, you can implicitly cast fine, but it causes an error when you try to explicitly cast.

struct B
{
    B() = default;
    B( B& rhs ) = default;
};

struct A
{
    operator B()
    {
        return B();
    }
};

int main()
{
    A a;
    B example = a;    //fine
    B example2 = static_cast<B>(a);    //error
}

The error is:

error C2440: ‘static_cast’: cannot convert from ‘A’ to ‘B’

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

message : No constructor could take the source type, or constructor overload resolution was ambiguous

The problem only appears if you define the copy constructor in the B structure. The problem goes away, though, if you define the move constructor, too, or make the copy constructor take in a const B& ( B( const B& rhs ) ).

I think the problem is that the explicit cast is ambiguous, but I don’t see how.

I was looking at a similar problem, here, but in that case I could easily see how the multiple options for casting led to ambiguity while I can’t here.

>Solution :

static_cast<B>(a);

This expression is an rvalue, more loosely described as a temporary value.

The B class has no suitable constructor. The B( B &rhs) constructor is not suitable, mutable lvalue references don’t bind to temporaries, hence the compilation failure.

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