I'm a C# programmer new to the D language. I'm a bit to confused with OOP in the D programming language.
Assuming that I have the following class:
public class A {
protected void foo() {
writefln("A.foo() called.");
}
};
public class B : A {
public override void foo() {
writefln("B.foo() called.");
}
};
The protected
modifier means that I can access the .foo()
method just on inherited class. So why does this D program compile normally?
Here is the equivalent in C#.NET:
using System;
public class A {
protected virtual void foo() {
Console.WriteLine("a.foo() called.");
}
};
public class B : A {
public override void foo() {
Console.WriteLine("b.foo() called.");
}
};
public class MainClass {
public static void Main(string[] args) {
A a = new A();
B b = new B();
a.foo();
b.foo();
}
};
It don't compile and given the following error message (as expected):
test.cs(10,30): error CS0507:
B.foo()': cannot change access modifiers when overriding
protected' inherited member `A.foo()'
Can someone explain this D behavior?
There's no purpose in preventing the override. The derived class could implement a trivial forwarding function that allows access. Consider:
public class A {
protected virtual void foo() {
writefln("A.foo() called.");
}
};
public class B : A {
protected override void foo() { // OK
writefln("B.foo() called.");
}
public void call_foo() {
foo(); // But I allowed public access anyway!
}
};
Thus, even though I didn't redefine the access level of foo
, I still allowed public access to it and there's nothing you can do about it. Allowing the redefinition is just simpler.