athos athos - 2 months ago 8
C++ Question

How to prevent a derived class object under base class pointer calling a public nonvirtual function defined in base class but overridden in derived?

Suppose base class

B
has a nonvirtual public function
f()
, which is unfortunately overridden by derived class
D
.

Then there's a
D
object
d
passed to a
B
pointer
pB
.

Is there a way to prevent calling
pB->f()
?

Answer

If you can change B, you can either make f virtual, or make it forward to a virtual protected do_f, or various other things.

If you can't change B, though you can't stop it's public method being called, and you can't somehow intercept a call to a non-virtual base class method.

Comments