Reputation: 414
Basically, I have 3 functions The first and second functions is to check whether ignition is true or false. The third function basically is to check if ignition is on, the speed cannot be greater than 65, if the speed is greater than 65, it will "Fix" that speed at 65. Whereas, if the ignition is turn off, the speed will be 0.
However, in my code, I did a if else statement. When I print the part where ignition is turn off, the value I got is 65. It suppose to be 0.
May I know what's wrong with my code?
car.h
#ifndef car_inc_h
#define car_inc_h
#include <iostream>
#include <string>
using namespace std;
class Car {
bool isIgnitionOn;
int speed;
public:
void turnIgnitionOn();
void turnIgnitionOff();
void setSpeed(int);
void showCar();
};
#endif
car.cpp
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
void Car::turnIgnitionOn() {
this->isIgnitionOn = true;
}
void Car::turnIgnitionOff() {
this->isIgnitionOn = false;
};
void Car::setSpeed(int speed) {
if (isIgnitionOn == true) {
if (speed >= 65) {
this->speed = 65;
}
else {
this->speed = speed;
}
}
else if (isIgnitionOn == false){
this->speed = 0;
}
};
void Car::showCar() {
if (isIgnitionOn == true) {
cout << "Ignition is on." << endl;
cout << "Speed is " << speed << endl;
}
else if (isIgnitionOn == false) {
cout << "Ignition is off" << endl;
cout << "Speed is " << speed << endl;
}
};
main.cpp
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
int main() {
Car myCar;
myCar.turnIgnitionOn();
myCar.setSpeed(35);
myCar.showCar();
myCar.setSpeed(70);
myCar.showCar();
myCar.turnIgnitionOff();
myCar.showCar();
return 0;
}
Upvotes: 0
Views: 2488
Reputation: 36401
speed
is never reset to 0. You can add this->speed=0
in turnIgnitionOff
which is more logical afterall.
Upvotes: 3