tags:

views:

41

answers:

2

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?

+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
thanks for ur kind answer. But still we can achieve this by simple inheritance? whats the main purpose behind using a virtual function?
NayeemKhan
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
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
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
+2  A: 

To implement Polymorphism in OO hierarchies.

nonnb
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
Agreed, although one could argue that conceptually Polymorphism relates to IsA inheritance extension, whereas implementing an Interface is a contractual obligation.
nonnb