9

both abstract and virtual are going to be override in child class than whats a difference.

is it Virtual method have body and abstract is just a signature ????

BreakHead
  • 10,480
  • 36
  • 112
  • 165
  • As an aside, partial methods, in contrast to abstract methods, allow you to create methods without implementations that do not need to be overridden. – Brian Mar 16 '10 at 13:43

3 Answers3

31

is it Virtual method have body and abstract is just a signature ????

Exactly. The point is that virtual methods can be overridden in derived classes, while abstract methods must be overridden. Likewise, a class that has at least one abstract method must itself be abstract, i.e. it cannot be instantiated directly since its implementation is (partially) missing.

Finally, every abstract method is also virtual by implication. virtual basically just means that the method is dispatched at runtime to the correct class, and so it can be overridden to implement runtime polymorphism.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Since abstract methods MUST be overwritten, they are in fact a contract like interfaces and code would compile unless you implement them correctly, so it is a way to get the users of your code to implement code they must implement, especially if they are lazy, correct? – Xaisoft Jul 19 '12 at 18:44
  • @Xaisoft Correct, but virtual (non-abstract) methods also form a contract since a contract is from the perspective of using classes (= clients). All that’s important is that a client can use the functions of a class that it advertises. – Konrad Rudolph Jul 19 '12 at 19:03
  • 2
    I agree, but what I meant was that if you declare a method virtual, a client does not have to implement it even though they should. Also a virtual method can have default behavior. A client has to implement an abstract method and it can't have default behavior. It seems the only reason you would go the abstract route vs the virtual route was if you really really wanted to enforce a method be implemented and the onus be put on the client. – Xaisoft Jul 19 '12 at 19:32
  • @Xaisoft Ah yes. That’s it precisely. – Konrad Rudolph Jul 19 '12 at 19:34
20

Abstract means you MUST override it. Virtual means you CAN override it. More or less.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 4
    Adding to that: With abstract methods in your class your whole class will be abstract which means you cannot create instances of this class, only of derived non-abstract subclasses. –  Mar 16 '10 at 13:40
1

I agree with both answers here, so I won't repeat them. But here's a link that might help.

10.6.3 Virtual, sealed, override, and abstract accessors

Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162