An abstract function cannot have 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.
Now, read these lines to understand about the abstract/virtual functions
Abstract Function
- An abstract function has no implementation. It can only be declared. This forces the derived class to provide the implementation of it
- Abstract means we MUST override it.
- An abstract member is implicitly virtual. Abstract can be called as pure virtual in some of the languages.
- An
abstract
modifier can be used withclasses
,methods
,properties
,indexers
andevents
.
Virtual Function
- Virtual Function has an implementation. When we inherit the class we can override the virtual function and provide our own logic, but it is not mandatory to override virtual methods.
- We can change the return type of Virtual function while implementing the function in the child class(which can be said as concept of Shadowing).
- Virtual means we CAN override it means a
virtual
method can be overridden or cannot be overridden bychild
class
C# Example of Abstract class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Abstract_Method
{
class Program
{
static void Main(string[] args)
{
childclass ch = new childclass();
ch.sum();
Console.ReadKey();
}
}
}
abstract class baseclass
{
public int num = 5;
public abstract void sum();
}
//child class inherited baseclass
class childclass : baseclass
{
//childclass implemnets sum method of abstract class with abstract method
public override void sum()
{
Console.WriteLine("Total Sum : " + num * num);
}
}
Output:
Total Sum : 25
C# Example of Virtual
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Virtual_Methods
{
class Program
{
static void Main(string[] args)
{
child1 ch1 = new child1();
ch1.message();
child2 ch2 = new child2();
ch2.message();
Console.ReadKey();
}
}
}
class baseclass
{
public virtual void message()
{
Console.WriteLine("Base class Virtual Method");
}
}
class child1 : baseclass
{
public override void message()
{
Console.WriteLine("Child 1 class");
}
}
class child2 : baseclass
{
}
Output:
Child 1 class
Base class virtual method