Is it valid to "hide" a base class virtual function by making it pure virtual in derived classes?

It is clearly allowed and supported by the standard (cf, for example, this online C++ standard draft), and thus clearly not undefined behaviour:

10.4 Abstract classes

5 [ Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. — end note ]

The effect is that your class B becomes abstract and any subclass - if it shall not be abstract, too - must define f() then; the implementation in class A can still be invoked through A::f(), such that it is - from the perspective of reusing the implementation - not pointless.


This will safely achieve the goal of requiring the author of C to provide an implementation for f().

I would query why this is needed — if the base implementation is not "valid" in your design then why does it exist, and/or why is it virtual?

They can still invoke A::f(), anyway, so whether this can be deemed "hiding" is open to debate.


my question whether this is a valid C++ or just "works" (such as undefined behaviours)?

The behaviour of the program is well defined.

effectively making A::f() more or less pointless.

Of course, if you never call a function, then defining the function is unnecessary indeed. To clarify, the function would have to be declared pure virtual if you did choose to omit the definition (the opposite is not true; you can define a pure virtual function).