casting class pointer

Jonathan M Davis jmdavisProg at gmx.com
Thu Nov 18 14:39:58 PST 2010


On Thursday, November 18, 2010 14:20:01 Jesse Phillips wrote:
> I usually avoid using pointers and classes together (actually I don't use
> pointers very much). But using 'in' on an associative array provides a
> pointer.
> 
> In any case, I ended up casting the pointer to the class type. (The
> simplified example isn't showing the behavior). The results were not good.
> I'm not sure exactly what happened but the code is something like this:
> 
> import std.stdio;
> 
> class A { string label; /* ... */ }
> 
> class B : A {
>     B[string] all;
>     string[] stuff;
> }
> 
> void main() {
> 	 auto b = new B();
> 	 b.label = "Fish";//Filler
> 	 b.stuff ~= "Cool huh";//Filler
> 	 b.all["hello"] = b;//Filler
> 
> 	 auto hi = "hello" in b.all;
> 
> 	 auto foo = cast(B) hi;
> 	 foreach(s; foo.stuff) {
> 		writeln(s);
>     }
> }
> 
> The result was that b.label wasn't the same, and printing out stuff
> resulted in a bunch of garbage. The questions I have are, should casting a
> class pointer to a class change its behavior so it just gives you the
> class? Is is there a use case for the current behavior? And should I
> bother working to reproduce this?
> 
> Maybe to! could be made to handle this, and upcasting?

Just dereference the pointer. I believe that in effect you have a pointer to a 
reference, not a pointer to an Object. Regardless of what it does internally 
though, the way to get at the object is to dereference it. If you had

auto foo = *hi;

then foo would be a reference to B, which is what you were trying to get.

- Jonathan M Davis


More information about the Digitalmars-d mailing list