Reputation: 6425
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()
?
Upvotes: 0
Views: 104
Reputation: 67812
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
, 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.
Upvotes: 1
Reputation: 15154
Your question essentially asks, “How do I make a function virtual?” You don’t give a reason why you can’t just do that, but maybe you can’t change the declaration of B
.
If B
has at least one virtual function, you could use RTTI to check if *pB
is really a D
and cast it to D&
if so. You cannot make existing code that takes a B*
do so; if your daughter class breaks when you call it as a B
, it breaks the contract of that interface.
Otherwise, it might be possible to determine that *pB
is a D
somehow by calling the B
interface, but that would be some rigmarole specific to B
and D
.
Upvotes: 0