1

I am trying to assign -1.4 to a double in an object c4 of the Complex class using the setRealPart method. However it gives me an error.

Here is the relevant code:

Prototype:

void setRealPart(double &);

Definition:

void Complex::setRealPart(double &real)
{
real = this->rpart; 
}

Implementation:

c2.setRealPart(-1.4);`

Consturctor:

Complex::Complex(double realpart,double impart)
{
rpart = realpart;
ipart = impart;         
}

The error I receive is: No known conversion for argument from double to double& 2. No matching function call setRealPart(double)

Scholar
  • 293
  • 3
  • 8
  • 16
  • 2
    You can't bind a temporary to a non-const reference. You're trying to assign `this->rpart` to `-1.4`, too, which makes no sense at all. – chris Oct 15 '13 at 21:11
  • 2
    Why are you using `double&` and not `double`? – David G Oct 15 '13 at 21:11

2 Answers2

4

When you pass a non-const reference to a function, the function is expected to be able to modify the element passed in. The signature of setRealPart suggests that the caller should be able to modify whatever you pass in (which is, of course, wrong: setters are not supposed to modify their arguments).

I am trying to assign -1.4 to a double in an object c4 of the Complex class

Your assignment goes the wrong way then, too: you should be assigning this->rpart = real, not the other way around.

Since this is a setter, the best approach would be removing the ampersand, and pass the double by value:

void Complex::setRealPart(double real)
{
    this->rpart = real; 
}

Finally, since you are not planning to modify the value of real passed in, consider declaring it const, like this:

void Complex::setRealPart(const double real)
{
    this->rpart = real; 
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You cannot bind a non-const lvalue reference to an rvalue, which is what you are attempting to do here:

c2.setRealPart(-1.4);

You need to either take a const reference. Besides that, your assignment is the wrong way around. This would work:

void Complex::setRealPart(const double &real) { rpart = real; }
//                        ^^^^^

or take the double by value:

void Complex::setRealPart(double real) { rpart = real; }
juanchopanza
  • 223,364
  • 34
  • 402
  • 480