Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract method declaration - virtual?

On MSDN I have found that it is a error to use "virtual" modifier in an abstract method declaration. One of my colleagues, who should be pretty experienced developer, though uses this in his code:

public abstract class BusinessObject   
{
    public virtual void Render(){}
    public virtual void Update(){}
}

Also it correct or not?

like image 493
Mocco Avatar asked Mar 18 '11 10:03

Mocco


3 Answers

It can make sense if the abstract class is providing an optional point where inherited classes can change the behaviour.

So this way the inherited classes will not be forced to implement it but they can if they need to.

Usually this method is called by the abstract class:

public AddFoo(Foo f)
{
   // ...
   OnAddedFoo(f);
}

Here it makes sense to have OnAddedFoo as virtual and not abstract.

like image 117
Aliostad Avatar answered Nov 09 '22 22:11

Aliostad


I guess the MSDN means you can't use the virtual and abstract modifier on a method at the same time.

You can either do

public virtual void Render() {}

which means that an inheriting class can override this method.

Or you can do

public abstract void Render();

which means that an inheriting class must override this method.

like image 5
herzmeister Avatar answered Nov 09 '22 20:11

herzmeister


Those aren't abstract methods, they're empty default ones. The difference is you don't HAVE to override them (if you don't, nothing will happen).

It might help your understanding to see them formatted like:

public abstract class BusinessObject   
{
    public virtual void Render()
    {

    }

    public virtual void Update()
    {

    }
}
like image 4
Rob Fonseca-Ensor Avatar answered Nov 09 '22 20:11

Rob Fonseca-Ensor