How a class can know the current reference of itself?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 4 02:58:34 PDT 2017


On Friday, 4 August 2017 at 09:38:59 UTC, Pippo wrote:
> I'm trying to do something like this:
>
> ------------
> module mylib.classA;
>
> class A
> {
>   @property string myproperty;
>   void function(ref A a) callToMyFunction;
>
>   void myfunction()
>   {
>     callToMyFunction(ref this);
>   }
> }
>
> ------------
> module myapp;
>
> import mylib.classA;
>
> int main()
> {
>   A a = new A();
>
>   a.callToMyFunction = &myFunction;
>
>   a.myfunction();
> }
>
> void myFunction(ref A a)
> {
>   writefln(a.myproperty);
> }
>
> ------------
>
> but (clearly) cannot compile. How can I get the same result?
>
> Thank you in advance.

Your first error is actually this line:

callToMyFunction(ref this);

You can't use ref in a function call, only in function 
declarations. But once that's fixed, you've got other errors in 
the code you've posted -- you've declared main to return int, but 
you return nothing; you're using writefln without importing it.

Also, class references are *already* references, so you don't 
need to declare the function parameters as ref. Finally, although 
this is not an error, @property has no effect on member 
variables. It only applies to member functions. Also, you never 
assign a value to myProperty, so even when the errors are fixed 
nothing is printed.

Here's code that compiles and works as you expect:

class A
{
   string myproperty;
   void function(A a) callToMyFunction;

   void myfunction()
   {
     callToMyFunction(this);
   }
}

void main()
{
   A a = new A();

   a.callToMyFunction = &myFunction;

   a.myproperty = "Hello";
   a.myfunction();
}

void myFunction(A a)
{
   import std.stdio : writefln;
   writefln(a.myproperty);
}

Although you might change it to this:

class A
{
   private string _myproperty;
   private void function(A a) callToMyFunction;
	
   this(string prop) { _myproperty = prop; }
   @property string myproperty() { return _myproperty; }

   void myfunction()
   {
     callToMyFunction(this);
   }
}

void main()
{
   A a = new A("Hello");

   a.callToMyFunction = &myFunction;

   a.myfunction();
}

void myFunction(A a)
{
   import std.stdio : writefln;
   writefln(a.myproperty);
}





More information about the Digitalmars-d-learn mailing list