Re: new virtual functions

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 12/16/04


Date: Thu, 16 Dec 2004 08:35:02 -0000

headware <dkland@cox.net> wrote:

<snip>

> It makes sense to me that cRef.f() prints out "D.f()", that is basic
> polymorphism. What doesn't make that much sense to me is why aRef.f()
> prints out "B.f()". Why should a reference of type A pointing to an
> object of type D call B.f()? I realize that it has to do with the fact
> that f() is declared as new virtual in C. What I don't understand is
> why this is the correct behavior. Why would you even want to do
> something like this? How could this be used?

B.f() overrides A.f(), which is basically what you're calling when you
use aRef.f(). C.f() and D.f() are completely separate methods to A.f()
and B.f() as far as the compiler is concerned.

As for why/when you'd want to use it - very rarely, basically. The
usual situation would be if you've got a library class and a class
you've derived from it. You've put in a method called Foo(), and then
in the next version of the library that class gains a method called
Foo() as well, which might be meant to do something completely
different. You don't want to override the library class's Foo() method,
because then the library class would be expecting it to do one thing
and it would actually do another, but you still want your code which
uses your Foo() method to compile and run properly.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • Re: a case for multiple inheritance
    ... and overrides the write functions to change ... the compiler would optimize it so that the double function call would be ... private new void Foo ... The cast not much ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: a case for multiple inheritance
    ... the compiler would optimize it so that the double function call would be ... private new void Foo ... The cast not much ... This means that if method A1 overrides ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: a case for multiple inheritance
    ... and overrides the write functions to change ... the compiler would optimize it so that the double function call would be ... private new void Foo ... The cast not much ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: new virtual functions
    ... > B.foverrides A.f, which is basically what you're calling when ... > and B.fas far as the compiler is concerned. ... You've put in a method called Foo(), ... > because then the library class would be expecting it to do one thing ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Sacla loop: a new loop implementation
    ... >> Finally, once the foo macro receives its argument, then based on what ... >> depending on how the macro is defined. ... transformations and optimizations deep in the bowels of the compiler, ... > available at macroexpansion time. ...
    (comp.lang.lisp)