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 can't conversion to non-scalar types be performed if a suitable assignment operator exists?

struct Foo {
    int val;
    Foo() : val(-1) {}
    explicit Foo(int val_) : val(val_) {}
    Foo& operator=(int val_) { val = val_; return *this; } 
    operator int () const { return val; }
};

int main()
{
    Foo foo = 1; // error
    Foo foo2;
    foo2 = 2; // works fine
    return 0;
}

error: conversion from 'int' to non-scalar type 'Foo' requested
     Foo foo = 1;

The code should be self-explanatory. I would like to understand why the direct assignment is illegal when a suitable assignment operator has been defined.

>Solution :

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

Unlike foo2 = 2;, Foo foo = 1; is not assignment, but initialization. Only constructors would be considered (to construct foo). The appropriate constructor Foo::Foo(int) is marked as explicit then can’t be used in copy initialization like Foo foo = 1;.

If you make Foo::Foo(int) non-explicit then the code would work; direct initialization (which considers explicit constructor) like Foo foo(1); works too.

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