I'm a C++ programmer starting with D and I'm having some trouble understanding the access qualifiers for D classes. Consider the following example:
import std.stdio;
class Foo {
private void aPrivateMethod()
{
writeln("called aPrivateMethod");
}
protected void aProtectedMethod()
{
writeln("called aProtectedMethod");
}
public void aPublicMethod()
{
this.aPrivateMethod();
this.aProtectedMethod();
}
}
void main(string[] args)
{
Foo foo = new Foo();
foo.aPublicMethod(); // OK to call it from anywhere
foo.aPrivateMethod(); // Must not be allowed to call it outside Foo
foo.aProtectedMethod(); // Should only be callable from within Foo and derived classes
}
I would expect the previous code to fail compilation, since it is calling private and protected methods of class Foo
in an external function. However, this is not the case, since the example above compiles and runs without errors or warnings on DMD v2.063.2. Clearly the keywords have different meaning from those of C++.
My questions are:
1) How to make a method and/or variable private to a class so that only the class in question can access it.
2) How to make a method and/or variable protected, so that only the class in question and its derived classes can access it.
the access modifiers are module/file level (only exception is protected)
to remove access to a class put it in its own mudule:
foo.d
import std.stdio;
class Foo {
private void aPrivateMethod()
{
writeln("called aPrivateMethod");
}
protected void aProtectedMethod()
{
writeln("called aProtectedMethod");
}
public void aPublicMethod()
{
this.aPrivateMethod();
this.aProtectedMethod();
}
}
main.d
import foo;
void main(string[] args)
{
Foo foo = new Foo();
foo.aPublicMethod(); // OK to call it from anywhere
foo.aPrivateMethod(); // compile error: Must not be allowed to call it outside foo.d
foo.aProtectedMethod(); // compile error: Should only be callable from within foo.d, Foo and derived classes
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With