✅ Understanding virtual keyword
Hi, I am familiar with inheritance and polymorphism but I struggle to understand the benefit of the virtual keyword. The idea behind the virtual keyword is to be able to provide a default implementation but also being able to possibly override that implementation in inheriting types. But we can do the exact same thing with just regular methods, so does virtual only exist to express clearer intend that methods shall be reimplemented in inheriting types by other developers or what is the purpose of that keyword?
10 Replies
But we can do the exact same thing with just regular methodsWell, no you can't You can't override non-virtual/abstract methods.
or hide with
new
then, my bad
still same question thohiding is not the same thing as overriding
whats the difference?
If you have a reference to the base class, it will call the base class method with hiding in derived class.
While with virtual, it will always call the most derived method.
oh wow I didn't know that
I thought it would always use the most derived method
That's when it's virtual.
thinker227#5176
REPL Result: Success
Console Output
Compile: 705.157ms | Execution: 53.724ms | React with ❌ to remove this embed.
understood, thank you both very much
np