Hi this is for C++. Thank you in advance! Car Class Write a class named Car that
ID: 3697097 • Letter: H
Question
Hi this is for C++. Thank you in advance!
Car Class
Write a class named Car that has the following member variables (often called instance variables):
yearModel. An int that holds the car’s year model
make. A string that holds the make of the car
speed. An int that holds the car’s current speed
In addition, the class should have the following constructor and other member functions.
Constructor. The constructor should accept the car’s year model and make as arguments. These values should be assigned to the object’s yearModel and make member variables. The constructor should also assign 0 to the speed member variable.
Accessor. Appropriate accessor functions to get the values stored in an object’s yearModel, make, and speed member variables. accelerate. The accelerate function should add 5 to 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. DO NOT allow the vehicle speed to reach a negative number.
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 six times. After each call to the brake function, get the current speed of the car and display it.
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
class Car
{
private:
int yearModel;
string make;
int speed;
public:
Car(int, string, int);
int getSpeed();
int getModel();
int accelerate();
void brake();
};
Car::Car(int yearModel,string make)
{
this. yearModel= yearModel;
this.make=make;
this.speed=0;
}
int Car::getSpeed()
{
return speed;
}
int Car::accelerate()
{
speed += 5;
return speed;
}
void Car::brake()
{
if (speed > 5)
speed -= 5;
else
speed = 0;
}
int main()
{
int yearModel;
string make;
cout << "Enter year and make ";
cin>>yearmodel>>make;
Car myCar(yearModel, make);
for (int i = 0; i < 5; i++)
{
myCar.accelerate();
cout << "The speed of the car is: " << myCar.getSpeed() << endl;
for (int j = 0; j < 6; j++)
{
myCar.brake();
cout << "The speed of the car is " << myCar.getSpeed() << endl;
system("PAUSE");
return(0);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.