Operator must take 'void'

1.5k Views Asked by At

Suppose I have two classes:

// A struct to hold a two-dimensional coordinate.
struct Point
{
    float x;
    float y;
};

// A struct identical to Point, to demonstrate my problem
struct Location
{
    float x;
    float y;
};

I would like to implicitly convert a Location to a Point:

Point somePoint;
Location someLocation;

somePoint = someLocation;

So, I added this operator inside Point:

operator Point(Location &other)
{
    // ...
}

Upon which I compile with g++ 4.9.2 on Debian, and receive this error:

error: 'Point::operator Point(Location &other)' must take 'void'

It sounds like the compiler wants the operator to accept no arguments, but that doesn't seem right -- unless I'm using the operator incorrectly. What is the real meaning behind this error?

2

There are 2 best solutions below

3
On BEST ANSWER

User-defined conversions operators are defined as a member function for the type from which you want to convert to a different type. The signature is (inside Location class):

operator Point() const; // indeed takes void
// possibly operator const& Point() const;

Another possibility is to provide a converting constructor for Point:

Point(Location const& location);
1
On

Don't overload the operator(). What you want to do is create a custom constructor that takes a point. The compiler with call this when you do the assignment or overload the assignment operator.

   Location( Point& p){
            x = p.x;
            y = p.y;
   }

   Location& operator= ( Point& p){
            x = p.x;
            y = p.y;
            return *this;
   }

This will get this to compile

  Point somePoint;
  Location someLocation;

  somePoint = someLocation;
  Location loc = somePoint;