In other words, why doesn't the compiler just "know" that if the definition of a function is changed in a derived class, and a pointer to dynamically allocated memory of that derived class calls the changed function, then that function in particular should be called and not the base class's?
In what instances would not having the virtual keyword work to a programmer's benefit?
virtual
keyword tells the compiler to implement dynamic dispatch.That is how the language was designed.
Without such an keyword the compiler would not know whether or not to implement dynamic dispatch.
The downside of virtual
or dynamic dispatch in general is that,
- It has slight performance penalty. Most compilers would implement dynamic dispatch using vtable and vptr mechanism, where the appropriate function to call is decided through vtable and hence an additional indirection is needed in case of dynamic dispatch.
- It makes your class Non-POD.
One reason:
Consider base classes located in separate module, like library.
And derived classes in your application.
How would compiler knows during compiling the library that the given function is/must be virtual.
One of the main designing principles of C++ is that C++ does not incur overhead for features that are not used (the "zero-overhead principle"). This is because of a focus on high performance
This is why you need to opt in to features like virtual functions while in languages like Java, functions are virtual by default.
The compiler doesn't know, because it can't. It might be your intention, to not use virtual functions, because there's always a cost associated with every feature.