Shouldn't private methods be virtual too?
Steven Schveighoffer
schveiguy at yahoo.com
Tue Jun 10 06:29:17 PDT 2008
"Michel Fortin" wrote
> 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.
>
> Making Base's method public or protected changes the output to
> "Derived.foo" as I'd expect.
In answer to your subject, no. Private methods are methods used by a class
that declares it only, not by derived classes. That is the expectation that
an author should have when declaring a method private. If you want a method
to be overridable by derived classes, declare it protected.
In answer to your example, I agree there should be an error if you declare a
method as 'override private'.
-Steve
More information about the Digitalmars-d
mailing list