Sard
Sard

Reputation: 2385

Combining conversion constructor with operator overloading

Why is the conversion constructor not called implicitly for i2?

class NumString
{
    public:
        NumString(const char*  s)
        {
        }

        int operator*( int i)
        {
            return 42;
        }
};


int main(void)
{
    int i1 = (NumString) "string" * 2;  //OK
    int i2 =  "string" * 2;             //ERROR
}

Upvotes: 0

Views: 91

Answers (2)

Matteo Italia
Matteo Italia

Reputation: 126787

The expression "string" * 2 involves just a const char * and an int, why should the compiler consider NumString in any way?

If it worked like you expect, how would the complier be expected to choose the correct conversion if more than one class had a suitable converting constructor?

Upvotes: 5

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272507

Because the compiler doesn't invoke user-defined conversions where there aren't any user-defined types involved.

Upvotes: 5

Related Questions