Search code examples
dprivate-memberscompiled-language

How do I declare a private class member in D?


This program will echo "C". How do I disallow that?

import std.stdio;
void main() {
    class A {
        private void B() {
            writeln("C");
        }
    }
    auto D = new A;
    D.B();
}

Solution

  • In D, private is private to the module, not the class. So, if you want a piece of code to not be able to access a member of a class, that class must be in a different module.

    The only exception would be if the code does not have access to the class at all due to it being in a different scope (e.g. if you have another function in your module, it could not access A, because it's inside main). But as long as a piece of code has access to a class which is inside the same module, then it has access to all of its members.