0

Hello---

I've written a class where I would like to overload the equal sign (= sign) operator so that I can return a double during an assignment. The following code snippet shows what I would like to do, but for some strange (probably small) reason, it does not seem to work.

Here is the main function in the entry class of the program:

int main()
{
	Vertex v;
	double testval = v;  // error occurs here
return 0;
}

Here is the function in the Vertex.cpp file:

double Vertex::operator = (const Vertex &rhs)
{
        value = 10.564;
	return value;
}

Here is the code in the header file Vertex.h:

class Vertex
{
public:
	Vertex();
	double operator = (const Vertex &rhs);
private:
	double value;
};

However, at compile-time, the compiler complains that:

cannot convert 'Vertex' to 'double' in initialization

Why can't the compiler convert 'Vertex' to double? What am I doing wrong here?

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by nkinar
2

The operator= you define is for the Vertex class. It only applied when you assign something to a Vertex object. What you apparently want is an implicit conversion:

class Vertex
{
public:
	Vertex();
	operator double() { return value; }
private:
	double value;
};
Votes + Comments
Great post; and extremely enlightening!
0

That is great. Thank you very much, Narue! The implicit conversion works well, and this is exactly what I am looking for.

Edited by nkinar: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.