reference class parent's function

okibi okibi at ratedo.com
Mon Apr 30 05:30:09 PDT 2007


Frits van Bommel Wrote:

> 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();
> }
> ---

That runs at run-time and is all in one module. I need to have it run afterwards and the classes are in separate modules in the program.


More information about the Digitalmars-d-learn mailing list