Can't get my return to work right.

+1 Glenn Walker · September 13, 2014
I am currently working a problem from some C++ text for a gas pump.  I have a class in which I have a set of member functions.  One of them is called set gallons it's purpose is if the user enters 0 gallons the gallons will default to 20. and it looks like this:

    double setGallons(double gallons)
    {
        if (gallons <= 0)
        {
            gallons = 20;
        }
        cout << "gallons =" << gallons << endl;
        cout << endl;
        system("pause");
        return gallons;
    }

This is called from main using the following:

        cout << endl << "How many gallons would you like (Enter 0 for fillup): ";
        cin >> gallons;
        gasObject.setGallons(gallons);

I know that the function is being run because should I input any number greater than 0 it shows that number and that is what appears to be returned.  However, if I input 0 it runs and shows the gallons to be 20 but still appears to return 0.

At a guess I would say that actually nothing at all is being returned or something is happening to the returned value.  And the program is just using the input.

I have another mutator function, setZero() that resets the gallons to 0 for when the program is re-run and it works as advertised.

Is there anyone who can explain to me what I am doing wrong?

Post a Reply

Replies

Oldest  Newest  Rating
+1 Franz Schmidt · September 13, 2014
I'm on it, but could you post your class too ?
+1 Franz Schmidt · September 13, 2014
I would do it like this:
#include <iostream>
using namespace std;

class gas{
private:
double gallons;
public:
void setGallons(void);
double getGallons(void);
};
void gas::setGallons(){
cout << endl << "How many gallons would you like (Enter 0 for fillup): ";
cin >> gallons;
if (gallons <= 0){
gallons = 20;
}
cout << endl;
}
double gas::getGallons(){
return gallons;
}

int main(){
gas gasObject;
while (1){
gasObject.setGallons();
cout << "gallons = " << gasObject.getGallons() << endl;
}
return 0;
}

If you work with classes you should make variables (e.g. gallons) inside the class which are like properties for the objects.
  • 1

C++

107,058 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator