I don\'t really understand - when am I supposed to use virtual functions?I\'ll be glad if someone could explain it to me, thanks.
public abstract class Weapon
{
public virtual abstract FireOnTarget();
}
public class Pistol : Weapon
{
public override FireOnTarget()
{
LoadPowder();
LoadBullet();
CockIt();
PullTheTrigger();
}
}
public class SucideBomber : Weapon
{
public override FireOnTarget()
{
BuyTruck();
LoadWithC4();
DriveToTarget();
ActivateDetonator();
}
}
OK now you have two classes. The point is to refer to the virtual function without knowing what actual class is there, for example:
public void PerformFiring(Weapon W)
{
// do stuff
W.FireOnTarget();
// do more stuff
}
This method will use whichever object you send in, derived from Weapon, and call FireOnTarget on that object. For example:
Pistol p=new Pistol();
PerformFiring(p);