Group
Object-Oriented Programming in C++
Objective
1. Define a class named Vehicle with a boolean attribute to track whether the engine is on.
2. Implement a method to start the vehicle. If already started, display a message.
3. Implement a method to simulate braking by showing a message.
4. Implement a method to simulate driving. The vehicle must be started first to drive.
5. In the main function, create a Vehicle object and call its methods to demonstrate the behavior.
Implement a Vehicle class with methods to start, brake, and drive.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include input-output stream library
using namespace std;
// Define the Vehicle class
class Vehicle {
private:
bool engineOn; // Boolean to track if the engine is started
public:
// Constructor initializes the vehicle with the engine off
Vehicle() {
engineOn = false;
}
// Method to start the vehicle
void start() {
if (engineOn) {
// If the engine is already on, notify the user
cout << "The vehicle is already started." << endl;
} else {
// Start the engine
engineOn = true;
cout << "Vehicle started successfully." << endl;
}
}
// Method to brake the vehicle
void brake() {
// Display a message to simulate braking
cout << "Vehicle is braking." << endl;
}
// Method to drive the vehicle
void drive() {
if (engineOn) {
// If the engine is on, simulate driving
cout << "Vehicle is driving." << endl;
} else {
// If the engine is off, notify the user
cout << "Cannot drive. Please start the vehicle first." << endl;
}
}
};
int main() {
// Create an object of the Vehicle class
Vehicle car;
// Attempt to drive before starting
car.drive();
// Start the vehicle
car.start();
// Attempt to start the vehicle again
car.start();
// Drive the vehicle
car.drive();
// Apply the brakes
car.brake();
return 0; // End the program
}
Output
Cannot drive. Please start the vehicle first.
Vehicle started successfully.
The vehicle is already started.
Vehicle is driving.
Vehicle is braking.