Car Class using C++
Posted by Samath
Last Updated: January 07, 2021
  31740

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 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 speedmember variables.
  • Accessors. Appropriate accessor functions to get and set 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 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 brake function five times. After each call to the brake function, get the current speed of the car and display it.

Output:

 

Car.h

#ifndef CARH
#define CARH
#include <string>
#include <iostream>
 
using namespace std;
class Car
{
public:
Car(int year, string makee);
 
void brake();
 
void accelerate();
 
void setSpeed(int sp);
 
int getSpeed();
 
void setMake(string makee);
 
string getMake();
 
 
void setyearModel(int year);
 
int getyearModel();
 
 
private:
int yearModel;
string make;
int speed;	
};
#endif
 

Car.cpp

#include <iostream>
#include <string>
#include "Car.h"
 
using namespace std;
Car::Car(int year, string makee)
{
	yearModel = year;
	make = makee;
	speed = 0;
}
 
void Car::brake()
{
	speed = speed - 5;
}
 
void Car::accelerate()
{
	speed = speed + 5;
}
 
 
void Car::setSpeed(int sp)
{
	speed = sp;
}
 
int Car::getSpeed()
{
	return speed;
}
 
void Car::setMake(string makee)
{
	make = makee;
}
 
string Car::getMake()
{
	return make;
}
 
 
void Car::setyearModel(int year)
{
	yearModel = year;
}
 
int Car::getyearModel()
{
	return yearModel;
}
 

Driver.cpp

#include <iostream.h>
#include "Car.h"
 
int main(int argc, char *argv[])
{
	Car Toyota(2005, "rav4");
cout<<"Accelerate"<<endl;	
for(int i = 0; i < 5; i++)
{
	Toyota.accelerate();
	cout<<"Current Speed: "<<Toyota.getSpeed()<<endl;	
}
cout<<endl;
cout<<"Decelerate"<<endl;	
for(int i = 0; i < 5; i++)
{
	Toyota.brake();
	cout<<"Current Speed: "<<Toyota.getSpeed()<<endl;	
}
 
system("pause");
	return 0;
}
   
  
 
 
   

 
 
I like this pro. still