-3
bool Car::isEnoughFuel(int miles) const
{
drivableMiles = fuelGauge.getCurrentFuel() * MPG; // Error here
bool status = true;

if (miles > drivableMiles)
    status = false;
return status;
}

Error: Expression must be a modifiable lvalue.

Brian
  • 21
  • 3
  • 4
    Because that is what `const` means? Why are you trying to modify the state of an object in this function? – UnholySheep Oct 13 '18 at 15:29
  • 3
    `const` doesn't mean that this function returns a constant, it means that it **can operate on constant `this`**, so all members must not change in it, and it mustn't call any non-`const` function – user9335240 Oct 13 '18 at 15:32
  • Assuming that `drivableMiles`is a class member variable of `Car` you'll need to make it `mutable` when trying to change it from a `const` function` – πάντα ῥεῖ Oct 13 '18 at 15:33
  • Because I want to return that drivableMiles to use in my main funtion. – Brian Oct 13 '18 at 15:35
  • 1
    @Brian _"Because I want to return that drivableMiles to use in my main funtion."_ That doesn't primarily require your function to be `const`. You can use a copy instead of changing the member variable though. – πάντα ῥεῖ Oct 13 '18 at 15:37

1 Answers1

1

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. A constant member function cannot modify any non-static data members or call any member functions that aren't constant. (Source)

In the line drivableMiles = fuelGauge.getCurrentFuel() * MPG; you are trying to modify the object isEnoughFuel() is called on. You probably don't want to have your function as const. However one work around would be to using copies instead.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45