www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Alias variable from another class

reply Begah <mathieu.roux222 gmail.com> writes:
I made a little program to illustrate my confusion :

   import std.stdio;

   class _1 {
	  int i;
	
	  this(int n) {
		  i = n;
	  }
   }

   class _2 {
	  _1 instance;
	
	  alias twelve = instance.i;
	
	  this() {
		  instance = new _1(12);
	  }
   }

   void main() {
	  _2 two = new _2();
	  writeln(two.instance.i);
	  writeln(two.twelve);
   }

What i tried to do is create an alias in class _2 of a variable 
in class _1.
What i would like is :
   two.twelve
to extends to:
   two.instance.i
But the compiler complains it cannot find "this" :
   Error: need 'this' for 'i' of type 'int'

Any ideas?
Dec 13 2016
next sibling parent Ali <something something.com> writes:
I guess it's because you're accessing a member of _1 from inside 
a scope of _2 where nothing has been constructed yet? Someone 
more familiar with D would probably have a better answer on this 
part. I'm quite new :)

But a work around would be

class _2 {
	  _1 instance;
	
	  auto twelve()  property {
               return instance.i;
           }
	
	  this() {
		  instance = new _1(12);
	  }
   }
Dec 13 2016
prev sibling next sibling parent ketmar <ketmar ketmar.no-ip.org> writes:
On Tuesday, 13 December 2016 at 19:13:24 UTC, Begah wrote:
 Any ideas?
you can't.
Dec 14 2016
prev sibling parent Rene Zwanenburg <renezwanenburg gmail.com> writes:
On Tuesday, 13 December 2016 at 19:13:24 UTC, Begah wrote:
 Any ideas?
Closest you can get is wrapping it in a property. If you need to do this often you may be able to generate them, check the recent "Getters/Setters generator" thread in Announce for some inspiration.
Dec 15 2016