[R-pkg-devel] Inherited methods

Kevin R. Coombes kev|n@r@coombe@ @end|ng |rom gm@||@com
Fri Aug 16 19:25:36 CEST 2024


Hi,

I seem to have gotten myself confused about inheritance of S4 classes 
and the dispatch of inherited methods.

The core situation is that

  * The graphics package already defines the function "hist"
  * My package A creates an S4 generic "hist", using the existing
    function as the default method.
  * Package A also defines a class B with its own implementation of the
    method "hist". It exports both the generic method and the class B
    specific method.
  * Now I create a new package C. In that package, I define a new class
    D that inherits from class B. The implementation of "hist" for class
    B should do everything I want for class D, so I don't want to have
    to re-implement it.

My question: what do I have to do to enable users of package D to call 
"hist(B)" and have it work without complaint? After many go-rounds of 
changing the code, changing the NAMESPACE, and running "R CMD check" 
approximately an infinite number of times, I now have

NAMESPACE:
importMethodFrom("A", "hist")
exportMethod("hist")

R SCRIPT:
setClass("D", slots = c(some_extra_stuff), contains = "B")

setMethod("hist", "D", function(x, ...) {
   callNextMethod(x, ...)
   invisible(x)
})

Do I really need all that? Why do I even need *any* of it? Shouldn't I 
be able to leave out the implementation that just says "callNextMethod" 
and have the standard dispatch figure out what to call? Why does it want 
to call the default function if it knows there is a B-method? (And it 
must know it, since callNextMethod knows it.)

Confused,
    Kevin

	[[alternative HTML version deleted]]



More information about the R-package-devel mailing list