Storing a reference to the calling object

Mike Parker aldacron at gmail.com
Sat May 23 09:48:57 UTC 2020


On Saturday, 23 May 2020 at 09:27:46 UTC, Tim wrote:
> Hi all, I'm a little new to D and I'm wondering how I can store 
> a reference to the calling object. I want to create a reference 
> to an object's parent so that each time I go to update the 
> sprite, it is able to grab its position from the parent.
>
> So if I have:
>
> class Sprite{
>     /// Postional components of the sprite
>     int* x, y;
>     SDL_Surface* image_surface;
>     auto parent;
>
>     this(const char* path, auto parent){
>         writeln(*x);
>         this.parent = parent;
>     }
>
>     void update(){
>         // Copy loaded image to window surface
>         writeln("Sprites x: ",  *x);
>         SDL_Rect dstRect;
>         dstRect.x = parent.x;
>         dstRect.y = parent.y;
>         SDL_BlitSurface(image_surface, null, g_surface, 
> &dstRect);
>     }
> }
>
> And call it like so:
>
> sprite = new Sprite(path, this);
>
> How can I make this sort of thing work? Thanks a lot in advance 
> for the help!

Since you're using classes, one way is to use a common base class 
or an interface. But assuming "parent" is the owner of the Sprite 
instance, you might eliminate the dependency on the parent and 
have it update the Sprite's position when it's updated instead of 
maintaining a position separately.

class Parent {
    private Sprite sprite;

    void updatePosition(int x, int y)
    {
        sprite.x = x;
        sprite.y = y;
    }
}


More information about the Digitalmars-d-learn mailing list