Explicitly hide a base function in C++ -
c++11 introduced useful specifier override
explicitly override base virtual function. explicit hiding?
for example, consider code:
struct a: b { void f(); }
- if there virtual
void b::f()
code cause implicit overriding function. - if there non-virtual
void b::f()
code cause hiding function.
that is, meaning of code depends on existence , virtuality of void b::f()
.
question. how explicitly hide base function? want error if try hide virtual function.
such override
guard ensure there is virtual base function same prototype, need guard ensure there no virtual base function same prototype.
epic fail example:
#include <stdio.h> struct b { void f() {printf("hello\n");} void g() {f();} }; struct a: b { void f() {g();} }; int main() { a; a.f(); return 0; }
the program print "hello". if make b::f()
virtual program cause segmentation fault (infinite recursion). may real problem if b
class third-party , #include it, changing virtuality in third-party code may cause fault in code.
upd. found c# have feature via new
specifier. it's seems c++ have not (yet?).
what may use check base class :
// class check b::f() not virtual // struct requires class compiles, else struct should epic fails. struct checkinterfaceisnotvirtual_b : b { void f() = delete; };
it fail compile if b::f()
virtual :
g++:
error: deleted function 'virtual void checkinterfaceisnotvirtual_b::f()'
clang++:
error: deleted function 'f' cannot override non-deleted function
Comments
Post a Comment