Opt-out polymorphism?

Steven Schveighoffer schveiguy at yahoo.com
Mon Feb 14 06:22:57 PST 2011


On Sun, 13 Feb 2011 16:34:04 -0500, Sean Eskapp <eatingstaples at gmail.com>  
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?

You can make them templates.  Templates are not final, and are not virtual.

e.g.: (untested)


class A
{
     void foo()()
     {
         writeln("A");
     }
}

class B : A
{
     void foo()()
     {
         writeln("B");
     }
}

The huge *huge* drawback is this:

A a = new B;
a.foo(); // outputs "A"

So I don't see a very common use case for this.

-Steve


More information about the Digitalmars-d-learn mailing list