blah blah blah is here! blah blah » Close

up1down
link

I know that a virtual member enables any inheriting class to override the implementation of the member marked with a virtual.

Are there any differences between a virtual and a abstract member?

last answered 2 years ago

3 answers

up2down
link

implementation...

a virtual member (property / method) defines a body / implementation which inheritors can override.

an abstract member does not define a body / implementation and inheritors *must* implement them. also, abstract members can only be defined in abstract classes.

Elliot_S
400

your second statement should read "a abstract member" right?

MadHatter
2309

an abstract member

salman
510

@madhatter I edited your answer and changed it to 'abstract' as the 3rd sentence said 'a virtual member does not....' I have to add features into the system where it tells you who/what was modified.

MadHatter
2309

ah. by the time I saw the comment it had already been edited, so I was a bit curious. but yes that is what I meant.

up-1down
link

Frankly speaking, I found no "real" difference. When in both cases you ultimately override and change the definition in subclass, what's the use of defining it earlier?
It's bit of juggling the code?

up0down
link

there's a HUGE difference in a number of ways. virtual provides implementation to inheritors which does not have to be implemented by the inherited class where abstract doesn't. when you inherit from an abstract class (much like an interface) you are *required* to provide an implementation. inside an overridden abstract calling base.OverriddenMethod does nothing (and I wonder if you wouldn't get a compile error). the base class does nothing other than define the contract whereby each inheritor fulfill.

when creating a set of classes that can be inherited, extended and modified, you will want to share common implementation. there will also be functionality which will end up being implementation specific.

a good example of this is a sort algorithm. if you have a base sort class you wouldn't want to implement a sort algorithm as they're all implementation specific:

public abstract class SortAlgorithmBase {

public abstract Array Sort(Array array);
}

public interface ISortAlgorithm {
Array Sort(Array array);
}

salman
510

@madhatter this new answer really seems to be a reply to @sanjib's response. My suggestion would be to comment on sanjib's answer saying something like 'see my updated response' and then edit your original answer. Actually that means I have to let you delete your answer's hehe, another item on the todo!

MadHatter
2309

yea, I had the same thought right after I posted it, but unfortunately there's no delete (yet;). still getting the hang of the Q&A format

sanjib
226

Many many thanks MadHatter, I needed a little bit elaboration and in your second post I got that.

Feedback