Though we can get the feel of virtual function by inheriting a class and enhancing the functionality of the function in the base class, when should we go for virtual function?
views:
41answers:
2
+2
A:
Virtual methods should be used when you want to provide default behaviour in the base class. The child classes can then override this function and provide their own, more specific behaviour.
For example:
class Animal
{
public virtual void Say()
{
//default behaviour
Console.WriteLine("Animal makes generic noise");
}
}
class Dog : Animal
{
public override void Say()
{
//specific behaviour
Console.WriteLine("Dog barks.");
}
}
fletcher
2010-08-17 08:56:13
thanks for ur kind answer. But still we can achieve this by simple inheritance? whats the main purpose behind using a virtual function?
NayeemKhan
2010-08-17 09:11:21
Nayeem - in Fletcher's example, you could have a heterogenous collection of animal - some could be dogs, some cats, and some basic animals. If Animal.Say() wasn't virtual, then all the animals would make only the generic noise, unless they were specifically upcast first. With virtual and override, each animal instance will Say() to its overridden behaviour.
nonnb
2010-08-17 09:32:41
nonnb-ya , but in real work of programming when do we find that its necessary to go for virtual function? can u place an example
NayeemKhan
2010-08-17 09:52:17
I find logging to be a good example, the base class could implement the default of logging to a log file, but you could have a plugin that enables logging to the database. The plugin then overrides the default implementation with it's own. There's always going to be a file we can log to, but there may not always be a database.
fletcher
2010-08-17 10:06:43
While this is clearly a correct answer (+1), it should be added that, given your argument, interfaces would be an equally valid alternative (since the OP is talking about single-level "inheritance") that don't require explicitly virtual methods.
stakx
2010-08-17 09:03:37
Agreed, although one could argue that conceptually Polymorphism relates to IsA inheritance extension, whereas implementing an Interface is a contractual obligation.
nonnb
2010-08-17 09:29:50