smatter
smatter

Reputation: 29168

What is the exact need of virtual function is C#?

I understand that it provides a default implementation that the derived classes can override. But is that the exact purpose?

Upvotes: 0

Views: 279

Answers (5)

Rowland Shaw
Rowland Shaw

Reputation: 38130

The need is that derived classes can override, and it behaves as you'd expect.

The converse is when creating a method on a derived class, specifying the new keyword -- in this situation the version of the function that matches the type of the variable is used, so:

derived foo = new derived();
base foo2 = foo;

foo2.bar(); // If bar() is virtual, and overriden in derived, it will use that implementation.
foo.bar(); // if bar() is not virtual, this may be calling a completely different function, if derived defines a new version

Upvotes: 2

sharptooth
sharptooth

Reputation: 170479

You can now have a collection of references to base class objects and put references to derived classes objects there, call the virtual function through any of the references without knowing the actual derived class and have the most derived overriden function called each time. That's called polymorphism.

Upvotes: 2

P.K
P.K

Reputation: 19117

To achieve polymorphism.

Upvotes: 1

Anton Gogolev
Anton Gogolev

Reputation: 115691

No, this is not their exact purpose. Virtual functions are means of achieving type polymorphism in an Object-Oriented language.

Upvotes: 10

Svetlozar Angelov
Svetlozar Angelov

Reputation: 21660

Yes, this is the exact purpose

Upvotes: 2

Related Questions