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?
A virtual keyword in C++ is used to create a virtual function in C++. The virtual function is the parent class function which we want to redefine in the child class. The virtual function is declared by using the keyword virtual.
To override a method, the override keyword is mandatory not virtual . The difference is that you hide the method if you omit the virtual keyword, and not override it.
In Java, methods are virtual by default. In C#, they are not, and must be marked as virtual in order for polymorphism to work.
The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.
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,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With