Hi all,
i am back with another post.but this post is not about design patterns,but it is about one of the most trivial but important features of C# - virtual functions.
let me explain the theory first and then we can look into one example.
Inheritance is one of the most important aspects of Object Oriented Programming. the purpose of inheritance is to reuse the functionality and also to extend the functionality offered by the base class.
consider the example given below
namespace virtualFunctions
{
class baseClass
{
int i;
public baseClass()
{
}
public baseClass(int val)
{
i = val;
}
public void Add()
{
Console.WriteLine(i);
}
}
class DerivedClass : baseClass
{
int j;
public DerivedClass(int val)
{
j = val;
}
public void Add()
{
Console.WriteLine(j+20);
}
}
}
Now call will be like this
baseClass b = new DerivedClass(20);
b.Add();
output is 0 coz the Add() function of the baseclass is called.
reason : we are calling the Add() method using the baseclass object. So the Add() of the baseClass is called.
Modify the baseclass function to
public virtual void Add()
{
Console.WriteLine(i);
}
And the derived class function to
public override void Add()
{
Console.WriteLine(j+20);
}
C all using the same invoking call usedpreviously.
The output is 40 coz the derivedclass’ Add() Function is called because of using the virtual keyword.
Now the output is 40. why? because the function is virtual, the Add() method of the DerivedClass is called even if we call the Add() method using the BaseClass instance.
This is because when we have declared the function as virtual and overriden it.
so when we create a n instance of DerivedClass and then assign it to a baseclass object,
the runtime instance is considered when the Add() function is called.
Hope this helps us all to understand virtual functions better.
happy Coding!!!
No comments:
Post a Comment