Bug 12346 – Instantiating class with a private constructor results in a runtime error

Status
RESOLVED
Resolution
INVALID
Severity
major
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-03-11T04:25:00Z
Last change time
2014-03-12T00:50:09Z
Assigned to
nobody
Creator
slavo5150

Comments

Comment #0 by slavo5150 — 2014-03-11T04:25:25Z
/********** test.d ***************/ module test; abstract class DoNotInstantiate { private this() {} } class TestClass : DoNotInstantiate { uint value; } /************ main.d **************/ void main() { test.TestClass x; // <--- This should result in a compile-time error x.value = 10; // <--- Runtime error. }
Comment #1 by slavo5150 — 2014-03-11T04:53:03Z
Turns out you don't even need inheritance to reproduce the problem. /********** test.d ***************/ module test; class TestClass : DoNotInstantiate { private this() {} uint value; } /************ main.d **************/ void main() { test.TestClass x; // <--- This should result in a compile-time error x.value = 10; // <--- Runtime error. }
Comment #2 by slavo5150 — 2014-03-11T04:55:40Z
Last post had an error in the code. Use this instead. /********** test.d ***************/ module test; class TestClass { private this() {} uint value; } /************ main.d **************/ void main() { test.TestClass x; // <--- This should result in a compile-time error x.value = 10; // <--- Runtime error. }
Comment #3 by andrej.mitrovich — 2014-03-11T05:05:46Z
1: You're not instantiating the class. You need to use 'new' to instantiate it, via: ----- class TestClass { private this() {} uint value; } void main() { TestClass x = new TestClass(); x.value = 10; } ----- 2: This is a reference, not instantiation, it cannot be an error even if the reference type is of an abstract class: ----- abstract class AC { private this() {} } void main() { AC ac; // allowed } ----- 3: Private symbols are visible and usable in the entire module they're defined in. Please read the documentation before filing bugs, or use the D forums[1] if you have questions or want to learn about D. [1] : http://forum.dlang.org/group/digitalmars.D.learn
Comment #4 by slavo5150 — 2014-03-11T17:47:56Z
Comment #5 by andrej.mitrovich — 2014-03-12T00:50:09Z
(In reply to comment #4) > How ironic! > http://d.puremagic.com/issues/show_bug.cgi?id=4595 That's a proposed enhancement of the compiler.