www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 24090] New: private constructor should not be allowed

https://issues.dlang.org/show_bug.cgi?id=24090

          Issue ID: 24090
           Summary: private constructor should not be allowed
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: Michael.Shah tufts.edu

I have two files below in two different modules and a private constructor that
should NOT be called.

It looks like private does not prevent a constructor from being called.
'private' does work for member functions fine however.

Testing on DMD64 D Compiler v2.102.1 (I did not see anything on changelog
otherwise fixing this for earlier versions)

```
// main.d
module main;

import std.stdio;
import student;

void main(){
//    Works as expected -- public constructor
//    auto s = Student("mike",1234); // works
//    writeln(s);

    // Should not work, constructor is private
    auto s2 = Student(cast(string)"sue"); // should not work
    writeln(s2);
}
```

```
// student.d
module student;
import std.stdio;

struct Student{
    string  name;

    this(string _name, int _id){
        writeln("this(string _name,int _id");
        this(_name);
    }

    private this(string _name){
        writeln("this(string _name)");
        name = _name;
    }

    this(int _id){
        writeln("this(int _id)");
        id = _id;
    }

  private:
    int     id;
}

```

This looks like in 2018 there was an attempt to fix this, but not sure if it
was actually fixed or merged.
https://issues.dlang.org/show_bug.cgi?id=18979

--
Aug 17 2023