Search code examples
c++oopcastingoperator-overloadingassignment-operator

Can you 'overload a cast' in C++ OOP?


Well, the WinAPI has a POINT struct, but I am trying to make an alternative class to this so you can set the values of x and y from a constructor. This is hard to explain in one sentence.

/**
 * X-Y coordinates
 */
class Point {
  public:
    int X, Y;

    Point(void)            : X(0),    Y(0)    {}
    Point(int x, int y)    : X(x),    Y(y)    {}
    Point(const POINT& pt) : X(pt.x), Y(pt.y) {}

    Point& operator= (const POINT& other) {
        X = other.x;
        Y = other.y;
    }
};

// I have an assignment operator and copy constructor.
Point myPtA(3,7);
Point myPtB(8,5);

POINT pt;
pt.x = 9;
pt.y = 2;

// I can assign a 'POINT' to a 'Point'
myPtA = pt;

// But I also want to be able to assign a 'Point' to a 'POINT'
pt = myPtB;

Is it possible to overload operator= in a way so that I can assign a Point to a POINT? Or maybe some other method to achieve this?


Solution

  • This is the job of a type conversion operator:

    class Point {
      public:
        int X, Y;
    
        //...
    
        operator POINT() const {
            POINT pt;
            pt.x = X;
            pt.y = Y;
            return pt;
        }
    };