views:

152

answers:

5

Hi, There is a thing I do not understand well: when virtual method is called, the base method is called as well?

Because when I use public override WinForm OnPaint method, in its body base.OnPaint(e) is called. I do not understand it, I thought virtual methods overrides the original one. If it is not usually called, why it is called in this case? Thank you

+10  A: 

No, it is not called, if you don't call it explicitly from the derived class.

onof
A: 

when virtual method is called, the base method is called as well?

This depends whether you call base.XXX in the overridden method or not.

Darin Dimitrov
+5  A: 

when virtual method is called, the base method is called as well?

No.

Because when I use public override OnPaint(), in its body base.OnPaint(e) is called. I do not understand it, I thought virtual methods overrides the original one.

The developer chose to call base.OnPaint(e) and also do something else. In other words, the base implementation is something which you have at your hand in case it is useful to you - you can call it, and then do some additional specific work.

If the function body was only a call to the base, then it would be equivalent to not writing the overriding function at all.

Daniel Daranas
Hmm..its standard WinForm OnPaint method. Is it called because the base contains some low level graphical routines that actually draw?
Snake
@Snake: Your comment is very specific to the implementation of one function. I don't know why the base is always called but I can guess that there is something common that always needs to be done.
Daniel Daranas
For an OnPaint method, it is likely that your code is drawing something "on top" of the default graphical representation. That's why the base implementation of OnPaint may be call: to draw the background, etc.
Xavier Poinas
A: 

Sometimes you have code in the "base" method that is useful no matter which child method is being executed, then the children can just call the base method, but that's optional.

Unless you specifically call the base method, the child method gets called instead of the base rather than "as well as".

ho1
+1  A: 

I understand that, when you say "virtual method is called", you mean overriding method.

The answer is no. Whenever any version of the virtual method is called, it does not automatically call its base class methods. But sometimes you want to call them, so you include an explicit call to the base class method. Something like this:

class Base
{
  public virtual void VirtualMethod()
  {
    // Insert code here
  }
}

class Derived : Base
{
  public override void VirtualMethod()
  {
    // Insert code here
    base.VirtualMethod(); // Explicit call to the base class method
  }
}

If we had not included the instruction base.VirtualMethod();, the base class method would not be called when the derived class method is invoked.

Gorpik