Car Milleage

Car Milleage

Define a Car struct with private member variables make, model, year, and mileage. Add public getter and setter functions for these variables. Ensure the setter function for mileage prevents the mileage from being set to a lower value than the current mileage. Demonstrate the use of these functions in a program.

Answer

#include <iostream>
#include <string>

struct Car {
private:
    std::string make;
    std::string model;
    int year;
    int mileage;

public:
    // Constructor to initialize member variables
    Car(const std::string& car_make, const std::string& car_model, int car_year, int car_mileage)
        : make(car_make), model(car_model), year(car_year), mileage(car_mileage) {}

    // Getter for make
    std::string get_make() const {
        return make;
    }

    // Setter for make
    void set_make(const std::string& car_make) {
        make = car_make;
    }

    // Getter for model
    std::string get_model() const {
        return model;
    }

    // Setter for model
    void set_model(const std::string& car_model) {
        model = car_model;
    }

    // Getter for year
    int get_year() const {
        return year;
    }

    // Setter for year
    void set_year(int car_year) {
        year = car_year;
    }

    // Getter for mileage
    int get_mileage() const {
        return mileage;
    }

    // Setter for mileage with validation
    void set_mileage(int car_mileage) {
        if (car_mileage >= mileage) {
            mileage = car_mileage;
        } else {
            std::cout << "Mileage cannot be set to a lower value than the current mileage." << std::endl;
        }
    }

    // Print car details
    void print_details() const {
        std::cout << "Make: " << make << std::endl;
        std::cout << "Model: " << model << std::endl;
        std::cout << "Year: " << year << std::endl;
        std::cout << "Mileage: " << mileage << std::endl;
    }
};

// Code in "main" is just there to menonstrate
int main() {
    // Create an instance of Car
    Car myCar("Toyota", "Corolla", 2020, 15000);

    // Print initial car details
    std::cout << "Initial car details:" << std::endl;
    myCar.print_details();
    std::cout << std::endl;

    // Set new values
    myCar.set_make("Honda");
    myCar.set_model("Civic");
    myCar.set_year(2021);
    myCar.set_mileage(20000);

    // Print updated car details
    std::cout << "Updated car details:" << std::endl;
    myCar.print_details();
    std::cout << std::endl;

    // Attempt to set mileage to a lower value
    myCar.set_mileage(18000);

    // Print car details after invalid mileage update attempt
    std::cout << "Car details after invalid mileage update attempt:" << std::endl;
    myCar.print_details();

    return 0;
}
Questions