Search code examples
c++rinheritanceabstract-classrcpp

How to expose a pointer of an abstract class using Rcpp?


I am implementing an R package for a C++ library using Rcpp. The library implements several derived classes from an abstract class. A function initializes new derived classes and returns a pointer of it as an abstract class. Is it possible to get a similar construct for R using Rcpp without changing the C++ library?

Here is a simplified reproducible example:

#include <iostream>
#include <string>
using namespace std;

// abstract class
class Base {
  public:
    virtual ~Base() {}
    virtual std::string name() const = 0;
    virtual Base* getNew() const = 0;
};

// derived class
class Derived: public Base {
  public:
    Derived() : Base() {}
    virtual std::string name() const { return "Derived"; }
    virtual Derived* getNew() const { return new Derived(); };
};

Base *newDerived( const std::string &name ) {
  if ( name == "d1" ){
    return new Derived ;
  } else {
    return 0 ;
  }
};

int main( void ) {
    Base* b = newDerived( "d1" ) ;
    cout << b->name() << endl ;
    return(1);
}

The output of the compiled code is: Derived

My current version uses Rcpp::RCPP_MODULE and Rcpp::XPtr. However, this version is not usable like the C++ implementaion:

#include <Rcpp.h>
using namespace Rcpp;

//... Base and Derived class and newDerived function implementations ... //

// wrapper function for pointer
typedef Base* (*newDerivedPtr)(const std::string& name);

//[[Rcpp::export]]
Rcpp::XPtr< newDerivedPtr > getNewDerived(const std::string type) {
  return(Rcpp::XPtr< newDerivedPtr >(new newDerivedPtr(&newDerived)));
}

RCPP_MODULE(mod) {
  Rcpp::class_< Base >("Base")
  ;

  Rcpp::class_< Derived >("Derived")
    .derives<Base>("Base")
    .default_constructor()
    .method("name", &Derived::name)
  ;
}

An example execution:

(dv = new(Derived))
# C++ object <0x101c0ce20> of class 'Derived' <0x101b51e00>
dv$name()
# [1] "Derived"
(dvptr = getNewDerived("d1"))
# pointer: 0x101c82770> // WANTED: C++ Object <0x...> of class 'Base' <0x...>

Solution

  • Let me re-phrase the question: You have a class Derived with a non-public constructor. The only way to create an instance of this class is via the factory method newDerived. This factory method does not return a pointer to Derived but a pointer to Base, from which Derived is derived.

    If this is correct, then you can use the technique shown in expose class in Rcpp - factory instead of constructor. You have to make sure to expose the Base class though:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // abstract class
    class Base {
      public:
        virtual ~Base() {}
        virtual std::string name() const = 0;
    };
    
    // derived class
    class Derived1: public Base {
      public:
        Derived1() : Base() {}
        virtual std::string name() const { return "Derived1"; }
    };
    
    // derived class
    class Derived2: public Base {
      public:
        Derived2() : Base() {}
        virtual std::string name() const { return "Derived2"; }
    };
    
    Base *newBase( const std::string &name ) {
      if ( name == "d1" ){
        return new Derived1 ;
      } else if ( name == "d2" ){
        return new Derived2 ;
      } else {
        return 0 ;
      }
    }
    
    RCPP_MODULE(mod) {
      Rcpp::class_< Base >("Base")
        .factory<const std::string&>(newBase)
        .method("name", &Base::name)
      ;
    
    }
    
    
    /*** R
    (dv1 <- new(Base, "d1"))
    dv1$name()
    (dv2 <- new(Base, "d2"))
    dv2$name()
    */
    

    Output:

    > (dv1 <- new(Base, "d1"))
    C++ object <0x1cd3e60> of class 'Base' <0x1ea3560>
    
    > dv1$name()
    [1] "Derived1"
    
    > (dv2 <- new(Base, "d2"))
    C++ object <0x1fbb9f0> of class 'Base' <0x1ea3560>
    
    > dv2$name()
    [1] "Derived2"
    

    Note that I have added a second derived class, removed the unused getNewmethod, and renamed the factor method. This way appears more realistic to me.


    Original answer, which can now act as an alternative: I fear you will have to do all the automation provided by Rcpp Modules by hand, i.e. generate a class at R level and use the factory method for initialization. The following is an adaption of the code in the Rcpp Modules vignette plus Rcpp attributes for easier coding:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // abstract class
    class Base {
      public:
        virtual ~Base() {}
        virtual std::string name() const = 0;
        virtual Base* getNew() const = 0;
    };
    
    // derived class
    class Derived1: public Base {
      public:
        Derived1() : Base() {}
        virtual std::string name() const { return "Derived1"; }
        virtual Derived1* getNew() const { return new Derived1(); };
    };
    
    // derived class
    class Derived2: public Base {
      public:
        Derived2() : Base() {}
        virtual std::string name() const { return "Derived2"; }
        virtual Derived2* getNew() const { return new Derived2(); };
    };
    
    Base *newBase( const std::string &name ) {
      if ( name == "d1" ){
        return new Derived1 ;
      } else if ( name == "d2" ){
        return new Derived2 ;
      } else {
        return 0 ;
      }
    }
    
    
    //[[Rcpp::export]]
    Rcpp::XPtr< Base > getNewBase(const std::string type) {
      return(Rcpp::XPtr< Base >(newBase(type)));
    }
    
    //[[Rcpp::export]]
    std::string Base__name(Rcpp::XPtr< Base > ptr) {
      return ptr->name();
    }
    
    
    /*** R
    setClass("Base", representation( pointer = "externalptr"))
    Base_method <- function(name) {
      paste("Base", name, sep = "__")
    }
    
    setMethod("$", "Base", function(x, name) {
      function(...) do.call(Base_method(name), list(x@pointer, ...))
    })
    
    setMethod("initialize", "Base", function(.Object, ...) {
      .Object@pointer <- getNewBase(...)
      .Object
    })
    
    (dv <- new("Base", "d1"))
    dv$name()
    (dv <- new("Base", "d2"))
    dv$name()
     */
    

    Interesting output:

    > (dv <- new("Base", "d1"))
    An object of class "Base"
    Slot "pointer":
    <pointer: 0x19b83e0>
    
    
    > dv$name()
    [1] "Derived1"
    
    > (dv <- new("Base", "d2"))
    An object of class "Base"
    Slot "pointer":
    <pointer: 0x1c02600>
    
    
    > dv$name()
    [1] "Derived2"
    

    Note that I am using an S4 class here, while RCPP_MODULE creates a Reference Class. One could probably also use an RC for this. Would be an interesting learning exercise, since I haven't directly used RCs up to now. Also note that I use a very different XPtrthan you. I am not sure what you are trying to wrap there.