Search code examples
c#virtualoverriding

What does Virtual and Override do behind the scene


I just came to understand Virtual and Override is use for(I can't find a use for so long). Now I'm using them in Factory Patterns. So my question is what does Virtual and Override do behind the scene? I'm willing to go in to IL and Machine code stuff.


Solution

  • I cannot give you any insights as to how it is done in IL but the basic theory is simple.

    When the compiler sees a virtual method declaration, instead of attaching the method to the class, it adds it to what is called a vtable (a Virtual Method Table) for that class, which holds pointers to functions.

    Now since the vtable is a part of the class, it is inherited by its subclasses and thus the virtual methods are inherited as well. Now comes the override bit. When the compiler sees an override in a method declaration, it looks up the vtable, finds the method to override and changes the function pointer so that it points to the new definition.

    Thus, you get both an inheritance of methods from parent classes and the ability to change their definitions in child classes.

    For more information, see the Wikipedia article on the Virtual Method Table.