Considering a struct point
struct point{
int x;
int y;
int z;
}
and a class object
class object{
public:
std::vector<point> points;
int dimension_count;
void addPoint(point addedPoint);
};
I'd like to have several child classes, like
line
, plane
, and shape
depending on the dimension count.
However, what I would like to do doesn't seem to have a way to implement it in valid C++.
In addPoint()
, I'd like to automatically cast the this
pointer to a subclass, either upcasting or downcasting as necessary.
void object::addPoint(point addedPoint){
int tempDimensions = (int)(addedPoint.x != 0) + (int)(addedPoint.y != 0) + (int)(addedPoint.z != 0);
//this just casts to line, but it would handle dimensions 1, 2 and 3
if(tempDimensions != dimension_count){
if(tempDimensions == 1){
this = dynamic_cast<line*>(this);
}
}
I'm aware that that is not valid C++, but I was wondering if there are any ways to do this, or if I'm stuck with an if
statement at the beginning of each function, instead of using virtual
functions to handle each case.