Alex Goft Alex Goft -4 years ago 94
C++ Question

Unclear use of operator double()

I have a

Rectangle
class with conversion operators to both
double
and
std::string
:

class Rectangle
{
public:
Rectangle(double x, double y) : _x(x), _y(y) {}
operator std::string ();
operator double ();
private:
double _x, _y;
double getArea() {return _x * _y;}
};

int main()
{
Rectangle r(3, 2.5);
cout << r << endl;
return 0;
}


I don’t understand why
operator double()
is invoked, rather than
operator std::string()
.
As far as I know, according to C++ wikibook,
operator double
is used to convert
Rectangle
objects to
double
.

So what's going on here? Is it related to the fact that an
int
is passed to the constructor? If so, why?

Answer Source

You do not have an operator to output the rectangle to the stream. cout does have an overload that takes a double and your class can be implicitly converted to a double so that is chosen.

The reason the string overload is not selected and is not considered as an ambiguity is because operator << for a string is a member function and is not included in the member overload and non member overload set of cout. If we comment out the operator double we can see we get a compiler error.

If we want to have the operator string called then we would need to explicitly cast r into a string. Live Example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download