Search code examples
c++functionc++11virtualexplicit

Why is `explicit` not compatible with `virtual`?


struct A
{
    // error C2216: 'explicit' cannot be used with 'virtual'
    virtual explicit operator bool() const 
    {
        return true;
    }
};

struct B : A
{
    // error C2216: 'explicit' cannot be used with 'override'
    explicit operator bool() const override 
    {
        return false;
    }
};

int main()
{
    if (A())
    {}

    if (B())
    {}
}

My compiler is VC++ 2013 RC.

Why is explicit not compatible with virtual?

What's the rationale?


Solution

  • Looks like a bug, since the following quotes prove that they are indeed compatible, and I couldn't find anything to disallow it.

    12.3.2 Conversion functions [class.conv.fct]

    2) A conversion function may be explicit [...]
    [...]
    5) Conversion functions can be virtual.

    and

    7.1.2 Function specifiers [dcl.fct.spec]

    5) The virtual specifier shall be used only in the initial declaration of a non-static class member function; see 10.3.
    6) The explicit specifier shall be used only in the declaration of a constructor or conversion function within its class definition; see 12.3.1 and 12.3.2.