13
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?

xmllmx
  • 39,765
  • 26
  • 162
  • 323

1 Answers1

18

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • The reason for this bug is probably that pre-11 `explicit` could only be used with constructors, which cannot (or should not?) be virtual anyway, so they made the additional rule of disallowing `virtual` and `explicit` together right away and this rule was just not updated when introducing `explicit` operators in *VC 2013*. – Christian Rau Oct 14 '13 at 09:07
  • yeah But why can't I just create a virtual contructor in a base class, and later implement it in the actual class. – Melroy van den Berg Nov 21 '20 at 22:36