casting class pointer

Jesse Phillips jessekphillips+D at gmail.com
Thu Nov 18 14:20:01 PST 2010


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?



More information about the Digitalmars-d mailing list