views:

5375

answers:

6

Which is the more correct approach? In which cases is it recommended to use virtual or abstract?

+1  A: 

You must always override abstract function.

Thus:

  • abstract functions - when inheritor must provide its own implementation
  • virtual - when it is up to inheritor to decide
Rinat Abdullin
+1  A: 

An abstract function has to be overridden while a virtual function may be overridden.

j0rd4n
+21  A: 

An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.

BFree
+2  A: 

You may override a Virtual method, but you must override an abstract one.Look here

Quaky
+6  A: 

An abstract function has no implemention and it can only be defined on an abstract class. This forces the derived class to provide an implementation. A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class. So for example:

public abstract class myBase
{
    //If you derive from this class you must implement this method. notice we have no method body here either
    public abstract void YouMustImplement();

    //If you derive from this class you can change the behavior but are not required to
    public virtual void YouCanOverride()
    { 
    }
}

public class MyBase
{
   //This will not compile because you cannot have an abstract method in a non-abstract class
    public abstract void YouMustImplement();
}
JoshBerke
A: 

you can do modifications in a vertual function by inheriting that in child class.

Divya Makta