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?

Recommended Answers

All 2 Replies

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;
};
commented: 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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.