0

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.

Kevin
  • 300
  • 2
  • 13

1 Answers1

0

You can't change type of object at runtime, but you can change internal implementation of object at runtime. You can do something like this:

class base {
public:
  virtual void someFunc()= 0;
protected:
  std::vector<point> points;
};

class line {
public:
  line(base *old) {
    // convert from other versions here
  }
  virtual void someFunc() {
    ...
  }
};

class object {
public:
  void addPoint(point addedPoint); // This will be common function, but it can call in implementation specific if needed
  void someFunc() {pImpl->someFunc();} // This is "virtual" function
private:
  std::unique_ptr<base> *pImpl;
};

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){
               pImpl = std::make_unique<line>(pImpl.get());
          }
     }
}
sklott
  • 2,634
  • 6
  • 17