Mocco
Mocco

Reputation: 1223

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?

Upvotes: 10

Views: 3361

Answers (5)

Andrew Orsich
Andrew Orsich

Reputation: 53675

Follwing code means that you must ovveride this method in inherited class and you can't put some logic in abstract method body:

public abstract void Render();

But if you declare virtual method you can put some logic inside it and can ovveride

public virtual void Render()
{
     // you can put some default logic here       
}

Upvotes: 0

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

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()
    {

    }
}

Upvotes: 4

You probably refer to this sentence

You cannot use the virtual modifier with the static, abstract, private or override modifiers.

This mean that you can not use this in method declaration a method can't be at the same time virtual and abstract.

So the usage that you have presented is fine, because the class is abstract this mean that you can have there some abstract methods (with out implementation that have to be implemented by child class) and virtual method (with implementation that can be override in child class).

Upvotes: 2

herzmeister
herzmeister

Reputation: 11287

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.

Upvotes: 5

Aliostad
Aliostad

Reputation: 81660

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.

Upvotes: 9

Related Questions