r-lib / R6

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

instantiate inherited class #272

Open RMHogervorst opened 1 year ago

RMHogervorst commented 1 year ago

I have a base class with a initialize function. What I'd like to do is for that initialize function to create and return a child class ( a class that inherits from the base class.)

c <- baseclass$new("blablabla") 
class(c) # "BaseClass",  "BlablablaClass"

Unfortunately this does not work, I get the baseclass only back.

Right now I have to create a function that instantiates a class but it would be so much cleaner if that could happen from the baseclass.

Is this possible?

wch commented 1 year ago

Sorry, I don't think you can do this. When you call $new(), it always returns an instance of the class that $new() is called on.

Why not just call childclass$new()?

RMHogervorst commented 1 year ago

Yeah I was afraid of that.

why not just call childclass$new?

  1. I want to have one interface, the user shouldn't care about which specific childclass is called,
  2. Legacy reasons: there used to be 1 class that loaded specific configuration on initialisation (but in a clunky way).
RMHogervorst commented 1 year ago

Thanks!