Car class

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?

Specifically:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//PHILLIP RODGERS
//CS226; GORADIA


#include <iostream>
#include <iomanip>
#include <string>

using namespace 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; }
Can anyone help me with this?
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();
Last edited on
Oh, Duh. Cause I have have function that increases/decreases the speed, but I don't have a function that actually gets and displays it. Thanks!
Topic archived. No new replies allowed.