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

Douglas Bates bates at stat.wisc.edu
Wed Sep 14 21:08:18 CEST 2011


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?


More information about the Rcpp-devel mailing list