How to disable/hide constructor when using factory method?

Arafel er.krali at gmail.com
Thu Jan 24 12:52:47 UTC 2019


You are declaring the constructor, but not defining it, i.e. you're 
telling the compiler that it's in some other compilation unit.

The compiler won't complain, but the linker will.

If you replace:

> private this();

with:

> private this() {}

it should work.

A.

On 1/24/19 1:48 PM, JN wrote:
> 
> I expected that too, but it doesn't even work in the same module.
> 
> class Foo
> {
>      private this();
> 
>      static Foo makeFoo()
>      {
>          Foo f = new Foo();
>          return f;
>      }
> }
> 
> void main() {
> }
> 
> fails with:
> 
> onlineapp.o:onlineapp.d:_D9onlineapp3Foo7__ClassZ: error: undefined 
> reference to '_D9onlineapp3Foo6__ctorMFZCQzQr'
> onlineapp.d:7: error: undefined reference to 
> '_D9onlineapp3Foo6__ctorMFZCQzQr'
> collect2: error: ld returned 1 exit status
> Error: linker exited with status 1
> 
> I don't understand why is this a linker problem. My understanding is 
> that for some reason static methods don't have access to the private 
> constructor (they're not considered same module?). But even though, it 
> should error with something like "Foo.makeFoo() cannot access private 
> Foo.this()" rather than fail at linking.



More information about the Digitalmars-d-learn mailing list