I've read from C++ primer 5th ed. That a virtual
member function that won't throw (noexcept
) must be overriden as non-throwing function. The exception is if the virtual
member function is defined as a 'deleted' member.
So I've tried this:
struct Foo{
virtual void func() const noexcept = delete;
};
struct Bar : Foo{
virtual void func() const noexcept(false) override = delete; // or let the compiler make it implicitly a throwing function
};
But when I compile the code I get the error:
looser exception specification on overriding virtual function ‘virtual void Bar::func() const noexcept (false)’|
I've searched on cppreference and found the same idea:
If a virtual function is non-throwing, all declarations, including the definition, of every overrider must be non-throwing as well, unless the overrider is defined as deleted. Here is the code from cppreference:
struct B {
virtual void f() noexcept;
virtual void g();
virtual void h() noexcept = delete;
};
struct D: B {
void f(); // ill-formed: D::f is potentially-throwing, B::f is non-throwing
void g() noexcept; // OK
void h() = delete; // OK
};
And when I compile the program from cppreference I get the same error as my example. (apart from f()
which shouldn't compile). So consider I comment out void f();
in struct D
. the compiler complains the same for void h() = delete;
.
So What is wrong with my compiler? Thank you!
N.B: I've tried the code from cppreference on their website and commented out f()
in struct D
and the code didn't compile too?!! So is this an error on he website too?
Example with clang and gcc: https://www.godbolt.org/z/f7hzbG