Pointer to Object Questions

Kirk McDonald kirklin.mcdonald at gmail.com
Sat Dec 30 13:25:18 PST 2006


John Kiro wrote:
> OK, but why does the compiler accepts something like:
> 
>   Point* pp1 = &p1;
>   writefln("Accessing p1 using pp1: ( %d,%d )", pp1.m_x, pp1.m_y);
> 
> I mean it seems that the leftside of "." can be either an object
> reference (p1) or a pointer to an object reference (pp1). Is this
> indeed the case?
> 

Correct. D has no member indirection operator (->) as C and C++ do. You 
just use . for everything. (The compiler knows if you're talking about a 
pointer or not, and is smart enough to figure it out.)

> BTW, I tested the above 2 statements in main(), and the result was
> correct.
> 
> Anyway, I guess I have to give up using pointers to objects. (may be
> it's OK in structs, not classes??)
> 

Since classes are by reference, anyway, there's no good reason to throw 
around pointers to objects.

If you /really/ want a pointer to a class instance, you can cast the 
reference to a void*:

     Foo f = new Foo;
     void* ptr = cast(void*)f;

(This should reinforce the fact that class references are just 
pointers.) However, this is pretty darned hackish, and usually serves 
little purpose. (Once cast to void*, you can't use that void* to access 
members of the class without casting it back.) The only use I can think 
of for this is when keeping references to GC-controlled objects.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list