reference class parent's function

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Apr 30 05:25:02 PDT 2007


okibi wrote:
> Hello!
> 
> I was wondering if you could tell me how to reference a class's function from another class after the first class has created an instance of the second class. Take a look at this:
> 
> class1 {
>   class2 c2 = new class2();
>   public void writeFunc(char[] myStr) {
>     writef("%s", myStr);
>   }
> }
> 
> class2 {
>  ???.writeFunc("hello world"); 
> }
> 
> Any ideas?

Something like the following?
---
import std.stdio;

class class1 {
   class2 c2;
   // init needs to be in constructor since it allocates at run-time
   this() { c2 = new class2(this); }
   public void writeFunc(char[] myStr) {
     writefln("%s", myStr);
   }
}

class class2 {
     class1 c1;

     this(class1 c) { c1 = c; }

     void foo() {
         c1.writeFunc("hello world");
     }
}

void main() {
     auto c = new class1;
     c.c2.foo();
}
---


More information about the Digitalmars-d-learn mailing list