Page 1 of 1

OOP question

Posted: Wed Jan 10, 2007 12:31 am
by bhalterm
How can an object refer to itself? I tried to use "this" like I would in Java because I saw it done in the documentation for "unref" in the ObjectOrientedProgramming section, but the interpreter said it was an undeclared variable.

Re: OOP question

Posted: Wed Jan 10, 2007 1:34 pm
by ted
bhalterm wrote:I tried to use "this" like I would in Java because I saw it done in the documentation for "unref" in the ObjectOrientedProgramming section, but the interpreter said it was an undeclared variable.
Read the documentation of unref again and you will see that the example
shows "this" being used within the template, i.e. in that example it is a
private member of the object. Trying to refer to it in a statement that lies
outside of the object will produce an error message. I suppose you could
declare "this" as public, but offhand I don't see the utility of top level
invocations of "this" when any objref that points to the object should
suffice to refer to that object.

Posted: Wed Jan 10, 2007 4:34 pm
by bhalterm
Sorry, I was a little vague. I am trying to write a proc within the object that calls another object's proc with itself as one of the arguments. It's a common idiom in Java, so I was inclined to find a way to do this just out of habit. I can certainly find another way to do it. If I were to declare "this" as a private member of the object, is there an easy way to initialize it to refer the enclosing object?

object reference: this

Posted: Thu Jan 11, 2007 2:00 am
by ted
bhalterm wrote:If I were to declare "this" as a private member of the object, is there an easy way to initialize it to refer the enclosing object?
Declaring it should be enough--see page 383 of The NEURON Book.
Example:

Code: Select all

begintemplate Foo
  public myname
  objref this

  proc init() {
    myname()
  }

  proc myname() {
    print "I am ", this
  }
endtemplate Foo

NUM = 3
objref fap[NUM]
print "at creation"
for i=0,NUM-1 fap[i]=new Foo()
print "check existing"
for i=0,NUM-1 fap[i].myname()

Posted: Thu Jan 11, 2007 9:25 am
by bhalterm
AH HAH!!! Thanks!

Posted: Fri Jan 12, 2007 10:47 am
by ted
Right. So simple, yet, now as I think about it, so easy to overlook. Reading your original
question, I just assumed that you had declared "this" inside the template, and then tried
referring to it from outside--but that should probably have generated an error msg stating
that "this" is not a public member of the object class.