Alex Rivera | Logout

When is it appropriate to use virtual methods?

Asked 2011-05-19T13:16:45.740
21

I understand that virtual methods allow a derived class to override methods inherited from a base class. When is it appropriate/inappropriate to use virtual methods? It's not always known whether or not a class will be sub classed. Should everything be made virtual, just "in case?" Or will that cause significant overhead?

Edit
Report

2 Answers

7

When you design a class you should have a pretty good idea as to whether it represents an interface (in which case you mark the appropriate overrideable methods and destructor virtual) OR it's intended to be used as-is, possibly composing or composed with other objects.

In other words your intent for the class should be your guide. Making everything virtual is often overkill and sometimes misleading regarding which methods are intended to support runtime polymorphism.

answered 2011-05-19T13:21:26.207
-1

Have a look at Design Patterns. If your code/design is one of these or similar go use virtual function. Otherwise, try this

answered 2011-05-19T13:23:22.217

Your Answer