"this" reference not working?

orgoton orgoton at mindless.com
Sat Apr 7 04:34:17 PDT 2007


In my program I have these classes

---------------------------------------
module entity;
import indexes;

enum EntType : ubyte
{Pawn, Tower, Queen, Other}

class Entity{
	this()
	{
		index[this.type].add(this);
	}
	~this()
	{
		index[this.type].remove(this);
	}
	public static const EntType type=EntType.Other;
}
-----------------------------------------
The module indexes keeps track of how many and which objects I have created thus far so 
that I can process them sequentially. In order to increase search speed, I created an
array of indexes, one for each entity type.
The index has a .has(Entity target) method that checks if target is indexed.

-----------------------------------
module pawn;
import entity;

class Pawn:Entity
{
	this()
	{
		assert(this.type==EntType.Pawn);
		super();
		assert(index[this.type].has(this), "Pawn not correctly indexed"); //this fails
	}
	~this()
	{
		//super destructor gets called automagically, no need to remove myself from the index
	}
	public static const EntType type=EntType.Pawn;
}
-----------------------------------------

Add some other classes for the remaining EntType entries. Because Entity _may_ be instaciated it must have an index.add and because of overloaded ctors (such as this(coordinates) that I did not copy) the super() is _always_ called and consequently I have entities indexed on the wrong indexes.

On the D documentation, it states:
"Within a non-static member function, this resolves to a reference to the object for which the function was called."
The example works fine.

Obviously, this isn't working for ctors. Is this a bug? If not, any suggestions as to I might get my prog working?

Also, on a side note, in order to have variables read-only, I declare them has private or protected and then create a method like "getVar()". Why isn't there a keyword like "readonly type var" in which var is read only outside the scope of the class?


More information about the Digitalmars-d-learn mailing list