user6564029
user6564029

Reputation:

D - What does an access modifier on a constructor actually do?

Suppose I have the following code:

class Foo
{
    private this(int x){ }
}
void
main()
{
    auto f = new Foo(4);
}

To my astonishment, this actually compiles. I would expect a private constructor to be unusable outside of the class it's defined in, just like a method would, but that's clearly not the case. The language reference doesn't even mention access modifiers in the constructors' section.

So the question is twofold: what does an access modifier do when applied to a constructor (if it does anything at all), and how do I hide a ctor?

Upvotes: 2

Views: 88

Answers (1)

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25605

Access modifiers on constructors work exactly the same as access modifiers elsewhere... but the key thing to remember is that in D, the access control only applies outside the module. Everything in the same module can see everything else inside it too, but the private ctor would prevent construction outside the module.

This differs from many other programming languages. The idea is the D module lets you define helper classes without needing something like C++'s friend feature.

Upvotes: 4

Related Questions