When the virtual keyword is applied to a method the whole class becomes abstract.
Shouldn't the virtual or abstract keyword be applied to the class? It is a more intuitive design because it reflects what is actually happening from a compiler/semantic perspective.
Was there other considerations I am missing when the designers were making this decision?
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 (=0
) 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 found here: Why do we need virtual functions in C++?.
Note:
C++ does not have the concept of an interface (if this is what you need), but you can emulate it by declaring an abstract class where all methods are pure virtual. This might be the source of your confusion, but as explained above virtual methods can be used for other cases as well.
Also note that in C++ even if you have a class with only pure virtual methods, it can also have some data members, so if you want to mimik something like an interface in other langguages you should better avoid adding such data members that the language allows.