Virtual functions cannot be constexpr however, when a function is implicitly virtual through inheritance, the compilers I have tried don't complain about it.
Here is a sample code:
class A
{
    virtual void doSomething() {}
};
class B : public A
{
    constexpr void doSomething() override {} // implicitly virtual constexpr
                                             // but no compilation error
};
class C : public A
{
    virtual constexpr void doSomething() override {} // explicitly virtual constexpr
                                                     // compilation error
};
I tried it with gcc 7.2.0 and .clang 5.0.0
Are those compilers not compliant to the standard in this regard, or are implicitly virtual constexpr functions allowed ?
Can virtual functions be constexpr? Yes. Only since C++20, virtual functions can be constexpr .
constexpr functions are implicitly inline , but not implicitly static .
A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations. And when a value is computed at compile time instead of run time, it helps your program run faster and use less memory.
In C++11, constexpr member functions are implicitly const.
The compilers have a bug. Note that this has been fixed in clang 3.5 already, not sure why you don't get an error, because I do.
The standard is pretty explicit about this in [dcl.constexpr]p3:
The definition of a constexpr function shall satisfy the following requirements:
- it shall not be virtual;
 - [...]
 
It does't matter whether doSomething is implicitly virtual or not. In both cases, it is considered to be virtual, and so it violates the point above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With