Opt-out polymorphism?

Jonathan M Davis jmdavisProg at gmx.com
Sun Feb 13 17:29:39 PST 2011


On Sunday 13 February 2011 13:34:04 Sean Eskapp wrote:
> Is there a way to specify that a function is nonvirtual, but can still be
> "overriden" in base classes? e.g.
> 
> class A
> {
>     void foo()
>     {
>         writeln("A");
>     }
> }
> 
> class B : A
> {
>     void foo()
>     {
>         writeln("B");
>     }
> }
> 
> void main()
> {
>     (new A).foo();
>     (new B).foo();
> }
> 
> Should output:
> A
> B
> 
> Is there a way to do this?

No. It's potentially error-prone to do that, and allowing the programmer to 
specificy that sort of thing complicates things. C# allows you to choose whether 
a function is derived or not in a fairly clear manner, and C++ allows you to do 
it in a somwhat poor manner, but in D, the compiler makes all of the decisions 
about whether a function is virtual or not. That definitely simplifies things, and 
since in virtually all cases, you want virtual functions, it's not generally an 
issue.

The only ways that you're likely to be able to make a function non-virtual in a 
class are by making it private (which may or may not continue to make functions 
non-virtual, since that contradicts TDPL) and if you make a function final. But D 
takes the tact of either it's overridable and virtual, or it's non-overridable 
and non-virtual. So, you can't do what you're trying to do.

And honestly, in most cases, I think that what you're trying to do is just plain 
begging for bugs. It is kind of cool that C# found a relatively clean way to 
deal with it, but I honestly don't know what it's useful for. I'd be worried 
about a program which overrode non-virtual functions. It's highly likely to 
cause bugs.

 Jonathan M Davis


More information about the Digitalmars-d-learn mailing list