r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
404 stars 56 forks source link

Methods in cloned object can refer to wrong super object #155

Closed wch closed 5 years ago

wch commented 5 years ago

If there are three levels of inheritance, C1, C2, and C3, and a method defined in C1 is overridden in C2, but not in C3, then in a C3 object's clone, inside the method, the super object will refer to the wrong level -- it will refer to the C2 methods instead of C1.

In the example below, in the clone, the addx method from C2 gets called twice, when it should only get called once.

C1 <- R6Class("C1",
  public = list(
    x = 1,
    addx = function() {
      message("C1 addx")
      self$x + 1000
    }
  )
)

C2 <- R6Class("C2",
  inherit = C1,
  public = list(
    addx = function() {
      message("C2 addx")
      super$addx() + self$x + 10000
    }
  )
)

C3 <- R6Class("C3",
  inherit = C2
)

a <- C3$new()
b <- a$clone()

a$addx()
#> C2 addx
#> C1 addx
#> [1] 11002

b$addx()
#> C2 addx
#> C2 addx
#> C1 addx
#> [1] 21003