C++ class that creates a Car object and then calls the accelerate function five times.Then, call the brake function five times get the current speed of the car and display it
Download file
C++ class that creates a Car object and then calls the accelerate function five times.Then, call the brake function five times get the current speed of the car and display it
1 file(s) 1.52 KB
Not a member!
Create a FREE account here to get access and download this file
Car Class
Write a class named Car that has the following member 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 ca r’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
variables.
• 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.
Demonstrate the C++ 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.
Answer:
// Car class
#include <iostream>
#include <string>
using namespace std;
// Car class declaration
class Car
{
private:
int yearModel; // The car's year model
string make; // The car's make
int speed; // The car's current speed
public:
// Constructor
Car(int y, string m)
{ yearModel = y; make = m; speed = 0; }
// accelearate function
void accelerate()
{ speed += 5; }
// brake function
void brake()
{ speed -= 5; }
// Accessor functions
int getYearModel()
{ return yearModel; }
string getMake()
{ return make; }
int getSpeed()
{ return speed; }
};
int main()
{
// Loop counter
int count;
// Create a car object.
Car porsche(2006, "Porsche");
// Display the current speed.
cout << "Current speed: "
<< porsche.getSpeed()
<< endl;
// Accelerate five times.
for (count = 0; count < 5; count++)
{
// Accelerate and display the speed.
cout << "Accelerating...\n";
porsche.accelerate();
cout << "Current speed: "
<< porsche.getSpeed()
<< endl;
}
// Brake five times.
for (count = 0; count < 5; count++)
{
// Brake and display the speed.
cout << "Braking...\n";
porsche.brake();
cout << "Current speed: "
<< porsche.getSpeed()
<< endl;
}
return 0;
}
Leave a reply