I'm learning about classes and passing member variables to functions from the book "Starting out with C++: Early objects".
Right now, I'm working on a programming challenge in chapter 7 that I just can't seem to wrap my head around. My issue is I can't seem to pass the speed
variable to my accelerate()
function and get it to add 5 each time it's used.
I've tried modifying it several different ways, and am probably way off by now. In case you're not understanding what I'm doing, here are the instructions for the challenge:
Write a class named Car that has the following member variables:
year. An int that holds the car's model year.
make. A string object that holds the make of the car.
speed. an int that holds the car's current speed.
In additions, the class should have the following member functions.
Constructor. The constructor should accept the car's year and make as arguments and assign these values to the object's year and make member variables. The constructor should initialize the speed member variable to 0.
Accessors. Appropriate accessor functions should be created to allow values to be retrieved from an objects year, make and speed member variables.
Accelerate. The accelerate function should add 5 from the speed member variable each time it is called.
brake. The brake function should subtract 5 from the speed member variable each time it is called.
Demonstrate the class in a program that creates a Car object and then calls the accelerate function five times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function five times. After each call to the brake function, get the current speed of the car and display it.
Here is what I have as of now:
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
int year, speed;
string make;
void accelerate(int);
void brake(int);
string getMake(string);
int getYear(int);
int getSpeed(int);
Car(int year, string make, int speed = 0) {
}
Car() {
}
};
void Car::accelerate(int s) {
speed += 5;
cout << "Your speed is " << s << endl;
}
void Car::brake(int speed) {
speed -= 5;
}
string Car::getMake(string) {
return make;
}
int Car::getYear(int) {
return year;
}
int Car::getSpeed(int) {
return speed;
}
int main() {
Car myCar;
int mySpeed = 0;
myCar.getSpeed(mySpeed);
for (int i = 1; i <= 5; i++) {
myCar.getSpeed(mySpeed);
myCar.accelerate(mySpeed);
}
}