class classname(value); & class classname=value; difference when constructor is explicit

Posted by Mahesh on Stack Overflow See other posts from Stack Overflow or by Mahesh
Published on 2011-01-16T21:43:43Z Indexed on 2011/01/16 21:53 UTC
Read the original article Hit count: 134

Filed under:
|
|

When constructor is explicit, it isn't used for implicit conversions. In the given snippet, constructor is marked as explicit. Then why in case foo obj1(10.25); it is working and in foo obj2=10.25; it isn't working ?

#include <iostream>
class foo
{
    int x;
    public:
    explicit foo( int x ):x(x)
    {}
};

int main()
{
    foo obj(10.25);  // Not an error. Why ?
    foo obj2 = 10.25; // Error
    getchar();
    return 0;
}

error: error C2440: 'initializing' : cannot convert from 'double' to 'foo'

© Stack Overflow or respective owner

Related posts about c++

Related posts about constructor