Search code examples
oopconstructorthisd

Passing the this pointer to a constructor


I'm trying to write a program in D that involves a Server class which creates new Client objects when new clients join. I want to pass the server object to the clients when they created, however when later I try to access the Server object from the client, my program stops with error code -11. I've googled it but found nothing.

I've successfully recreated this behavior in the following snippet:

import std.stdio;



class Server
{
public:
    int n;
    Client foo() //Foo creates a new client and passes this to it
    {return new Client(this);}
}

class Client
{
public:
    this(Server sv) //Constructor takes Server object
    {sv=sv;}
    Server sv;
    void bar() //Function bar tries to access the server's n
    {writeln(sv.n);}
}

void main()
{
Server s = new Server; //Create a new server object
Client c = s.foo(); //Then ask for a client
//c.sv=s; //!!!If I leave this line in the source then it works!!!
sv.n=5; //Set it to a random value
c.bar(); //Should print 5, but instead crashes w/ error -11
}

If I uncomment the c.sv=s line, then is magically works, which I don't understand.

So why is that if I set sv in the constructor then it crashes, but if I set it later then it works?

EDIT: Adding writeln(sv) to the bar function prints null, so it can cause the crash. But why is it null?


Solution

  • {sv=sv;}

    This line is the mistake. It sets the local sv, not the class instance. Try this.sv = sv; instead to set the instance member to the local.

    edit: so since you never set the instance variable, it remains uninitialized - defaulting to null.