In: Computer Science
#include<iostream>
using namespace std;
class Car{
// Creating the variables in private
private:
// year
int yearModel;
// Manufacturer
string make;
//current speed
int speed;
// Creating public functions so that private varibles are
// indirectly accessible
public:
// parameterized constructor with year and make
// and sets those variables to class variables and sets speed = 0
Car(int year, string make){
yearModel = year;
make = make;
speed = 0;
}
// returns the year
int getYear(){
return yearModel;
}
// returns the make
string getMake(){
return make;
}
// returns current Speed
int getSpeed(){
return speed;
}
// increases speed by 5 units
void accelerate(){
speed += 5;
}
// decreases speed by 5 units
void brake(){
// speed should not be negetive
// so no action should be performed at this time
if( speed - 5 < 0 )
return;
// speed is reduces by 5 units
speed -= 5;
}
};
int main(){
// initializing the constructor
Car car(2020, "BMW");
// calling accellerate function 5 times
for(int i=1;i<=5;i++){
// accelerating car
car.accelerate();
// printing current speed
cout << "Accelerating, Current Speed = "<<car.getSpeed() <<endl;
}
cout <<endl;
// calling brakes function 5 times
for(int i=1;i<=5;i++){
// Applying brakes
car.brake();
cout << "Applying Breaks, Current Speed = "<<car.getSpeed() <<endl;
}
return 1;
}