[Rcpp-devel] External pointer to an instance of a C++ class

Dirk Eddelbuettel edd at debian.org
Wed Sep 14 21:48:36 CEST 2011


On 14 September 2011 at 14:08, Douglas Bates wrote:
| I discovered by accident that I can create an external pointer (Xptr)
| object to an instance of a subclass and use it as if it were a pointer
| to an instance of the class.
| 
| To be specific, the parent class is lmResp and the subclass is
| glmResp.  A few of the methods in the lmResp class are overridden in
| the definition of the glmResp class but most aren't.  So, for example,
| the methods to set and get the offset vector for a glmResp instance
| are inherited from the lmResp class.
| 
| I create an instance of a glmResp and return an external pointer to
| the instance to R where it is stored as a field in a reference class
| object.  I then use this external pointer to call methods on the C++
| class instance.
| 
| Without being aware of it I passed the external pointer to the glmResp
| as a pointer to an lmResp object when invoking an inherited method.
| When I did become aware that I was doing this, I was pleasantly
| surprised that it had worked.
| 
| In some way I think this is legitimate in that, IIRC, a pointer to an
| instance of a subclass can be used as a pointer to an instance of the
| parent class.
| 
| So the purpose of this posting is to ask if I am correct that this
| should be expected to work or should I expect that on some exotic
| compilers this will suddenly blow up on me?

In C++, it should work, it uses basic 'is-a' relationship (a la Meyers) --
see the 'Pizza' example here:
http://en.wikibooks.org/wiki/C++_Programming/Code/Design_Patterns#Factory_Method

But then you knew that already as evidenced by your (awesome!) lm() example
in RcppEigen.   So I am not sure I got your question...

Also, there was a gotcha, a thing to look out for, and I can't of course
remember what it was.  I think you have to be careful in terms of casting /
accessing between class and subclass.


In Rcpp, it should work just the same as the XPtr just gets passed around and
then cast with C++ rules, so back to the above.


But again, I may have missed your question entirely...

Dirk

-- 
New Rcpp master class for R and C++ integration is scheduled for 
San Francisco (Oct 8), more details / reg.info available at
http://www.revolutionanalytics.com/products/training/public/rcpp-master-class.php


More information about the Rcpp-devel mailing list