Untitled
unknown
plain_text
2 years ago
1.8 kB
16
Indexable
#include <iostream>
#include <string>
#include <ctime>
class Car {
private:
std::string company;
std::string model;
int year;
public:
// Constructor to initialize the object
Car(std::string comp, std::string mdl, int yr) : company(comp), model(mdl), year(yr) {}
// Getter functions
std::string getCompany() const {
return company;
}
std::string getModel() const {
return model;
}
int getYear() const {
return year;
}
// Setter functions
void setCompany(const std::string& comp) {
company = comp;
}
void setModel(const std::string& mdl) {
model = mdl;
}
void setYear(int yr) {
year = yr;
}
// Function to calculate the age of the vehicle
int calculateAge() const {
// Get the current year
std::time_t t = std::time(0);
std::tm* now = std::localtime(&t);
int currentYear = now->tm_year + 1900;
// Calculate and return the age
return currentYear - year;
}
};
int main() {
// Create two objects of the Car class
Car car1("Toyota", "Camry", 2018);
Car car2("Honda", "Civic", 2019);
// Display the details of the cars
std::cout << "Car 1 Details:\n";
std::cout << "Company: " << car1.getCompany() << "\n";
std::cout << "Model: " << car1.getModel() << "\n";
std::cout << "Year: " << car1.getYear() << "\n";
std::cout << "Age: " << car1.calculateAge() << " years\n\n";
std::cout << "Car 2 Details:\n";
std::cout << "Company: " << car2.getCompany() << "\n";
std::cout << "Model: " << car2.getModel() << "\n";
std::cout << "Year: " << car2.getYear() << "\n";
std::cout << "Age: " << car2.calculateAge() << " years\n";
return 0;
}
Editor is loading...
Leave a Comment