Why does this function not work?

I need to explain why a particular function does not work, and fix the error using only parentheses. I have a short main:

1
2
3
4
5
  	double a;
	Complex b(1, 1), c(2, 2);
	a = b * c.abs();
	cout << a << endl;
	return 0;


The Complex class represents a number x+yi. I have all the arithmetic functions overloaded, and two Complex numbers can be multiplied together, or they can be multiplied with a number. I also have the abs() function, which simply returns the absolute value of a Complex number in double form.

I put this code, along with the written class in my IDE and tested it using a different test main to test my functions, and everything works out fine. So I just need to find out why this particular line: a = b * c.abs(); doesn't work. Finally, I have to fix this line only using parentheses to change the evaluation order. Does anyone have any tips on how I can tackle this problem?
Last edited on
What isn't working? Also, what do you mean by "returns the absolute value of a Complex number in double form"? A complex number can't be a double whether it's positive or negative unless y is 0.
This particular line:

a = b * c.abs();

abs() calculates the absolute value of a Complex number. It returns this in double form. The formula for the absolute value of a Complex number (as given to me for this problem) is the square root of the real number ^2 + the imaginary number ^2.

So if I have 5+ 3i, the absolute value of it is square root of ((5^2)+(3^2)).

So abs returns that number as a double.

I need to multiply b (which is a Complex object) with the absolute value of c. However, this compiler gives me the error:

"No suitable conversion from "Complex" to "double" exists"

a is a double that has been declared but has no value assigned to it.
Hmm, and b * c.abs() would return a Complex object, and I can see that I can't assign an object to a double value since they are different.

But then I don't really understand the problem, because first I have to explain why this function doesn't work, which I just figured out why.

But then the next part of the problem simply states : "Change the evaluation order of a = b * c.abs(), by inserting parentheses.
1
2
// a = b * c.abs();
a = ( b * c ).abs();
JLBorges is right. The first statement finds the modulus of c (c.abs), then tries to multiply it by b. The compiler complains because there is no function to multiply a "Complex" by a double.
The second statement uses parentheses to specify the order of evaluation: first multiply b by c, then find the absolute value of the result.
Topic archived. No new replies allowed.