Saturday, February 12, 2011

Basic Instincts: Virtual Method; New; Override

Ever wondered how defining a function as virtual impacts its working at run time and how is it intervowen with the access modifiers NEW and OVERRIDE.

The following sample chapter from Vijay Mukhi will make things very clear. The chapter is in form of explanations of snippets of code, but it is very effective

http://www.vijaymukhi.com/documents/books/csbasics/chap9.htm

Essentially to summarize the chapter: Defining a function as virtual gives the power of deciding at run- time which method will be called based upon the assigned object i.e if you have a base class A which is inherited by class B and class C as shown below

Class A
{
public virtual One()
{......
......
}

public Two()
{......
......
}

public virtual Three()
{......
......
}
}


Let's assume that class B inheriting from Class A overrides methods One and Three. Now if an object of class B is assigned to a variable of type A; then on calling a.One() and a.Three(); the implementation of these methods in class B will be called.
Since Two() is not virtual, there is no question of overriding it in B and hence a.Two() will always results in calling the implementation of the method within class A.

Also if a virtual method is not overriden in inherited class; by default the access modifier NEW is assumed thus breaking the chain of the virtual method in inherited classes from thereonwards.

But even if the chain is broken, down the line a new chain can be established if any of the inheriting class down the line, defines the same method as virtual and other classes under it override the implementation of the method. But as specified this would be a new chain.

No comments:

Post a Comment