Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ : implications of making a method virtual

Should be a newbie question...

I have existing code in an existing class, A, that I want to extend in order to override an existing method, A::f().

So now I want to create class B to override f(), since I don't want to just change A::f() because other code depends on it.

To do this, I need to change A::f() to a virtual method, I believe.

My question is besides allowing a method to be dynamically invoked (to use B's implementation and not A's) are there any other implications to making a method virtual? Am I breaking some kind of good programming practice? Will this affect any other code trying to use A::f()?

Please let me know.

Thanks, jbu

edit: my question was more along the lines of is there anything wrong with making someone else's method virtual? even though you're not changing someone else's implementation, you're still having to go into someone's existing code and make changes to the declaration.

like image 469
jbu Avatar asked Mar 17 '26 12:03

jbu


1 Answers

If you make the function virtual inside of the base class, anything that derives from it will also have it virtual.

Once virtual, if you create an instance of A, then it will still call A::f.

If you create an instance of B and store it in a pointer of type A*. And then you call A*::->f, then it will call B's B::f.

As for side effects, there probably won't be any side effects, other than a slight (unnoticeable) performance loss.

There is a very small side effect as well, there could be a class C that also derives from A, and it may implement C::f, and expect that if A*::->f was called, then it expects A::f to be called. But this is not very common.

But more than likely, if C exists, then it does not implement C::f at all, and in which case everything is fine.


Be careful though, if you are using an already compiled library and you are modifying it's header files, what you are expecting to work probably will not. You will need to recompile the header and source files.

You could consider doing the following to avoid side effects:

  1. Create a type A2 that derives from A and make it's f virtual
    • Use pointers of type A2 instead of A
    • Derive B from type A2.
    • In this way anything that used A will work in the same way guaranteed

Depending on what you need you may also be able to use a has-a relationship instead of a is-a.

like image 118
Brian R. Bondy Avatar answered Mar 19 '26 02:03

Brian R. Bondy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!