I have two D classes in one module. I would like class A to have a property, which can only be accessed from class A and class B. How would I do this?
class A {
int a = 5; // Make this accessible to, and only to, B.
}
class B {
this(in A pA) {
int b = pA.a;
}
}
private
is private to a module, not a class. So, marking a symbol as private
makes it so that only stuff in that module can access it.
package
makes it so that only stuff in the same package can access the symbol.
protected
makes it so that only stuff in that class and in classes derived from that class can access the symbol (unlike the others, protected
makes no sense outside of classes).
public
makes it so that anything can access the symbol.
private
and package
functions are never virtual, whereas protected
and public
functions are always virtual unless the compiler is able to determine that they don't need to be (which at this point, can pretty much only happen when the function is final
and doesn't override a function in a base class).
So, as long as your two classes are in the same module, and their members are private, they can access each others members - as can anything else within the module - but nothing outside the module can access them. There is no way to restrict access within a module except for when the symbol is local to a function, so if you want to make it so that one class cannot access the members of another, then you're going to need to put them in separate modules.