15.11 When to Use Virtual?
Whether you mark a method with virtual or not depends on the design you choose. In C++, it is not common practice to make all methods of all classes virtual by default. There can be reasons for and against making each individual method virtual, and the same applies to each individual class. This is somewhat different from the reasons for choosing between methods and free functions: encapsulation with methods is better, and so you usually opt for them. When it comes to deciding whether to use virtual methods or not, the matter is not quite as clear. Take the following hints as decision aids for your design:
-
Some classes primarily serve the purpose of holding data together. They are not part of a hierarchy. Without ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access