Search code examples
c++classconversion-operator

Operator must take 'void'


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?


Solution

  • 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);