Mr. Smith
Mr. Smith

Reputation: 4506

Are override methods considered virtual methods?

Taken from Eric Gunnerson's blog "virtual functions are not inlined", but what qualifies as a virtual method? MSDN defines it as:

"When an instance method declaration includes a virtual modifier, that method is said to be a virtual method. When no virtual modifier is present, the method is said to be a non-virtual method." - MSDN Source

Strictly speaking, a derived class with the override method public override void SomeMethod(){}" does not contain the word virtual, so could it be inlined?

Edit: Specifically, the question is whether the overrided method is a candidate for inlining, since the two links I've provided are too vague on overrided methods.

Upvotes: 1

Views: 210

Answers (2)

svick
svick

Reputation: 244767

From §1.6.6.4 Virtual, override, and abstract methods of the C# 4.0 specification (you were quoting an older version):

A virtual method can be overridden in a derived class. When an instance method declaration includes an override modifier, the method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of that method.

So, when you write an override method, you're not actually creating a new method, you're just overriding a method. And that one has to be virtual, so the method you're actually calling is virtual.

That being said, there are cases where a virtual method can be inlined: if the compile-time type of the object in question is sealed, then there is no doubt what code to execute. (I believe .Net actually does not use this optimization.)

But in other cases, virtual methods cannot be inlined.

Upvotes: 5

Phillip Scott Givens
Phillip Scott Givens

Reputation: 5464

Methods that override virtual methods are definitely virtual. In many ways, they are all the same method as the one they override. They use something called a vtable. They point of the blog that you reference is that the compiler will optimize what it can, but since a virtual/overridden method has a look-up involved, it cannot be simplified.

Upvotes: 0

Related Questions