I'm having a few problems with this code. I couldn't get it to work in time for class the other day and it has been bothering me.
When I compile this it tells me that current_speed (assuming they're referring to the one in int main() function) is being used without being initialized.
It then asks me if I want to continue or break. I select continue and it spits out this number always: -858993460
And it goes into the Y/N loop, which works fine. Where did I go wrong?
//PHILLIP RODGERS
//CS226; GORADIA
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
// CAR CLASS DEFINED
class Car
{
private:
int current_speed;
int year;
string make;
string model;
public:
Car(int, int, string, string);
int accelerate();
int brake();
};
//MAIN FUNCTION
int main()
{
//OBJECT CREATION
Car turboCar(0, 1994, "Toyota", "RX-S");
//STUFF FOR MENU & CAR OPERATIONS!
int current_speed;
int operationChoice;
char continueChoice;
//MENU CODE
do
{
cout << "Hello, welcome to car number one.\n";
cout << "What would you like to do with your brand new car?\n";
cout << "Press 1 to accelerate.\n Press 2 to brake.\n Choose now: ";
cin >> operationChoice;
if(operationChoice = 1)
turboCar.accelerate();
if(operationChoice = 2)
turboCar.brake();
cout << current_speed;
cout << "\n\nWould you still like to use the car?\n If so, press Y. If not, press N.\n Choice: ";
cin >> continueChoice;
}while((continueChoice == 'y') || (continueChoice == 'Y'));
return 0;
}
//CAR FUNCTION DEFINITIONS
Car::Car(int cs, int y, string m, string mo)
{
current_speed = cs;
year = y;
make = m;
model = mo;
}
int Car::accelerate()
{ return current_speed + 5; }
int Car::brake()
{ return current_speed - 5; }
You have current_speed defined in main, and you have current_speed defined in your class. These are two different variables and they don't communicate. This is a problem of scope.
To solve this create an accessor and eliminate current_speed from your main function
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// CAR CLASS DEFINED
class Car
{
private:
int current_speed;
int year;
string make;
string model;
public:
Car(int, int, string, string);
int accelerate();
int brake();
int getSpeed() { return current_speed; } // Added this:
};
Then in your main:
1 2 3 4
int current_speed;
...
cout << current_speed;cout << turboCar.getSpeed();