I thought I would post an example of using R.oo with inheritance and pass by
reference for future searches. With PerMore I am inheriting Person. Then I
am changing an object data memeber of an object of PerMore class using pass
by reference ('mimiced' by R.oo) in an object of AgeMultiplier. I change a
data member in the child class and the parent class for demonstration
purposes. This is me giving back to the community...hope it helps.

Moral of the story is use your sets and gets rather than obj$dataMember.

I am new to R.oo so if you know how to do this better or have some tricks
please email me at ccquant@g*m...@il.com.

setConstructorS3("Person", function(age) {
  if (missing(age))  age <- NA;

  extend(Object(), "Person",
    .age=age
  )
})

setMethodS3("getAge", "Person", function(this, ...) {
  this$.age;
})
setMethodS3("setAge", "Person", function(this,num, ...) {
  this$.age = num;
})
#..........................................................
setConstructorS3("PerMore", function(age,wt) {
  if (missing(age))  age <- NA;
  if (missing(wt))  wt <- NA;

  extend(Person(), "PerMore",
    .age=age,
    .wt=wt
  )
})

setMethodS3("getWeight", "PerMore", function(this, ...) {
  this$.wt;
})
setMethodS3("setWeight", "PerMore", function(this,w, ...) {
  this$.wt = w;
})
pc = PerMore(67,150)
pc$getWeight() #
pc$getAge() # 67
#...........................................................
setConstructorS3("AgeMultiplier", function(m,perobj) {
  if(missing(m))m=NA;
  if(missing(perobj))perobj=NA;

  extend(Object(), "AgeMultiplier",
    .m=m,
    .perobj=perobj,
    .AM=NA,
    .WM=NA
  )
})
setMethodS3("getPerObj", "AgeMultiplier", function(this, ...) {
  this$.perobj
})
setMethodS3("getAM", "AgeMultiplier", function(this, ...) {
  this$.AM
})
setMethodS3("getWM", "AgeMultiplier", function(this, ...) {
  this$.WM
})
 setMethodS3("doMultiplyAge", "AgeMultiplier", function(this, ...) {
  a = this$.perobj;
  this$.AM =  a$getAge()  * this$.m;
  a$setAge(this$.AM);
})
 setMethodS3("doMultiplyWeight", "AgeMultiplier", function(this, ...) {
  a = this$.perobj;
  this$.WM =  a$getWeight()  * this$.m;
  a$setWeight(this$.WM);  # a$wt = this$.WM;  <- that does not work on an
object that inheritance involved
})

p1 <- PerMore(67,150)
am1 =  AgeMultiplier(5,p1)
am1$doMultiplyAge()
p1$age  # 335
am1$AM  # 335
am1$getAM()  # 335
am1$doMultiplyWeight()
p1$wt  # doesn't work, I don't know why...
p1$getWeight() # 750
am1$WM  # 750
am1$getWM()  # 750
am1$doMultiply()
p1$age  # 335
am1$AM  # 335
am1$getAM()  # 335

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to