Shouldn't private methods be virtual too?

Jarrett Billingsley kb3ctd2 at yahoo.com
Tue Jun 10 06:06:37 PDT 2008


"Michel Fortin" <michel.fortin at michelf.com> wrote in message 
news:g2lnj9$1ig9$1 at digitalmars.com...
> The following example prints "Base.foo" (using GDC 0.24), even though we 
> have a Derived object and Derived's foo is declared as overriding Base's. 
> Is that expected behaviour?
>
> module test.privatevirtualfunction;
>
> class Base {
> private void foo() { writefln("Base.foo"); }
> }
>
> class Derived : Base {
> override private void foo() { writefln("Derived.foo"); }
> }
>
> int main(char[][] args) {
> Base base = new Derived;
> base.foo();
> return 0;
> }
>
> I understand that private currently makes the method non-virtual. I think 
> this would be fine with the C++ private concept where it limits the 
> member's usage to the current class, but I believe in D, where private 
> only limits usage to the current module, you should be able to override 
> that method in any class defined in the same module. If that's not the 
> case, then you should at the very least get an error with the above code.

I would expect an error too.  In most languages with this kind of protection 
scheme, overriding a base class method with a method that is more protected 
is an error.  It is in Java:

class Fark
{
    public void foo()
    {

    }
}

public class Bark extends Fark
{
    protected void foo()
    {

    }
}

Gives the error "foo() in Bark cannot override foo() in Fark; attempting to 
assign weaker access privileges; was public."  And if my memory serves me, 
C# works the same way.

Private methods should always be final.  They cannot be overridden by 
derived classes, even if they can be accessed by classes in the same module. 





More information about the Digitalmars-d mailing list