When setting up inheritance, its best to establish a base class with behavior shared with all the derived classes.
Then derived classes can inherit from the base class
class Rectangle : public Shape{
public:
Rectangle() : Shape() {}
public:
//this->length: points to length within base class, etc.
double area(){
return this->length * this->height;
}
};
class Triangle : public Shape{
public:
Triangle() : Shape() {}
public:
double area(){
return 0.5 * this->length * this->height;
}
};
The Rcpp function can then calculate the areas of the different shapes:
// [[Rcpp::export]]
double calculate_areas(std::string shape, double length, double height){
double out = 0;
if(shape == "rectangle"){
Rectangle rect;
rect.length = length;
rect.height = height;
out = rect.area();
} else if (shape == "triangle") {
Triangle tri;
tri.length = length;
tri.height = height;
out = tri.area();
} else {
Rcpp::Rcout << "Invalid shape" << std::endl;
}
return out;
}
All the code is combined into my_inheritance.cpp
in the
src
directory and can be run from r using
Rcpp::sourceCpp
Rcpp::sourceCpp("../src/my_inheritance.cpp")
calculate_areas("triangle", 6, 4)
## [1] 12
calculate_areas("square", 2, 2)
## Invalid shape
## [1] 0