www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - "constructor missing initializer for const field" when field is set inside an init function

reply =?iso-8859-1?Q?Robert_M._M=FCnch?= <robert.muench saphirion.com> writes:
This following code gives an error: "constructor a.this missing 
initializer for const field myThing"

class a {
	const myThing*;

	init(){
		myThing = initMyThing();
	}
	
	this(){
		init();
	}
}

I have to explicitly set the const field inside this(). As long as I 
only have one constructor that's OK. I prefer to have an init() 
function to collect all things to setup an object.

Shouldn't the compiler find out that myThing is set during construction 
in this case?

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster
Jan 04
next sibling parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Sat, Jan 04, 2020 at 03:50:54PM +0100, Robert M. Münch via Digitalmars-d
wrote:
[...]
 class a {
 	const myThing*;
 
 	init(){
 		myThing = initMyThing();
 	}
 	
 	this(){
 		init();
 	}
[...] In general, it's a very bad idea to name a member function or variable .init, because .init is supposed to be a bitwise copy of the initial state of a type. While the language currently doesn't regard it as an error to redefine .init to be something else, IMO it should, because it breaks a lot of assumptions in generic code, and in general just causes too much trouble to be worth it. I wouldn't be surprised if you came across compiler bugs if you redefine .init this way. If you didn't intentionally override .init, the best solution is to rename it to something that doesn't clash with the built-in expectations of .init, like initialize() or some such. That should fix your problem. T -- It is not the employer who pays the wages. Employers only handle the money. It is the customer who pays the wages. -- Henry Ford
Jan 04
prev sibling parent Paul Backus <snarwin gmail.com> writes:
On Saturday, 4 January 2020 at 14:50:54 UTC, Robert M. Münch 
wrote:
 This following code gives an error: "constructor a.this missing 
 initializer for const field myThing"

 class a {
 	const myThing*;

 	init(){
 		myThing = initMyThing();
 	}
 	
 	this(){
 		init();
 	}
 }

 I have to explicitly set the const field inside this(). As long 
 as I only have one constructor that's OK. I prefer to have an 
 init() function to collect all things to setup an object.

 Shouldn't the compiler find out that myThing is set during 
 construction in this case?
You could try something like this: enum string initThing = q{ myThing = initMyThing(); }; this() { mixin(initThing); }
Jan 05