79332220

Date: 2025-01-06 06:19:22
Score: 0.5
Natty:
Report link

When the virtual keyword is applied to a method the whole class becomes abstract.

This is not true. You can have concrete (non-abstract) classes with virtual method(s).
Only if you have a pure virtual method the class becomes abstract.

Why is the virtual keyword applied to methods instead of classes

I believe one of the reasons is that in C++ is it common to have the principle of "pay only for what you use".
Virtual methods use dynamic binding for invoking and this has some overhead (typical implementations use a v-table which introduces an additional level of indirection).
If you don't need dynamic binding for a specific method - don't declare it virtual and it will be statically binded.

This applies even for abstract classes - if you have a non virtual method in an abstract class, then when you invoke it on a derived class the binding will be static and you won't pay the dynamic binding overhead.

More info about static and dynamic binding can be foudn here: Why do we need virtual functions in C++?.

Reasons:
  • Long answer (-0.5):
  • No code block (0.5):
  • Ends in question mark (2):
  • Starts with a question (0.5): When the
  • High reputation (-2):
Posted by: wohlstad