149k views
5 votes
Create an application named CarDemo that declares at least two Car objects and demonstrates how they can be incremented using an overloaded ++ operator.

Create a Car class that contains the following properties:

Model - The car model (as a string)
Mpg The car's miles per gallon (as a double)
Include two overloaded constructors. One accepts parameters for the model and miles per gallon; the other accepts a model and sets the miles per gallon to 20.

Overload the ++ operator that increases the miles per gallon value by 1. The CarDemo application creates at least one Car using each constructor and displays the Car values both before and after incrementation.

1 Answer

0 votes

Answer:

Implementation of the Car class and a CarDemo application in C++:

#include <iostream>

#include <string>

using namespace std;

class Car {

private:

string model;

double mpg;

public:

// Constructor with model and mpg parameters

Car(string m, double mpg_val) {

model = m;

mpg = mpg_val;

}

// Constructor with only model parameter

Car(string m) {

model = m;

mpg = 20.0;

}

// Overloaded ++ operator

Car& operator++() {

mpg++;

return *this;

}

// Getter methods for model and mpg properties

string getModel() const {

return model;

}

double getMPG() const {

return mpg;

}

};

int main() {

// Create two Car objects using different constructors

Car car1("Toyota", 30.5);

Car car2("Honda");

// Display initial car values

cout << "Car 1 Model: " << car1.getModel() << endl;

cout << "Car 1 MPG: " << car1.getMPG() << endl;

cout << "Car 2 Model: " << car2.getModel() << endl;

cout << "Car 2 MPG: " << car2.getMPG() << endl;

// Increment car values using overloaded ++ operator

++car1;

++car2;

// Display incremented car values

cout << "After Incrementing:" << endl;

cout << "Car 1 Model: " << car1.getModel() << endl;

cout << "Car 1 MPG: " << car1.getMPG() << endl;

cout << "Car 2 Model: " << car2.getModel() << endl;

cout << "Car 2 MPG: " << car2.getMPG() << endl;

return 0;

}

Step-by-step explanation:

In this implementation, the Car class has two constructors, one that accepts parameters for the model and miles per gallon and another that only accepts a model and sets the miles per gallon to 20. The operator++ function overloads the ++ operator to increment the miles per gallon value by 1.

The CarDemo application creates two Car objects using each constructor and displays their properties before and after incrementation using the overloaded ++ operator.

User John Dalsgaard
by
7.7k points