write a C++ program. Create a class of a car owner. Overload input and outpur operators. Create a dynamic array of car owners. Write a function that prints it. Make sure it compiles.
Assistant
Here is a simple C++ program that defines a CarOwner class, overloads the input (>>) and output (<<) operators, creates a dynamic array of CarOwner objects, and includes a function to print the elements of the dynamic array:
cpp
#include <iostream>
#include <string>
class CarOwner {
private:
std::string name;
int age;
std::string carModel;
public:
// Default Constructor
CarOwner() : name(""), age(0), carModel("") {}
// Parameterized Constructor
CarOwner(std::string n, int a, std::string c) : name(n), age(a), carModel(c) {}
// Overloading the input operator
friend std::istream& operator>>(std::istream& in, CarOwner& owner) {
std::cout << "Enter owner's name: ";
in >> owner.name;
std::cout << "Enter owner's age: ";
in >> owner.age;
std::cout << "Enter car model: ";
in >> owner.carModel;
return in;
}
// Overloading the output operator
friend std::ostream& operator<<(std::ostream& out, const CarOwner& owner) {
out << "Name: " << owner.name << ", Age: " << owner.age << ", Car Model: " << owner.carModel;
return out;
}
};
void printCarOwners(CarOwner* owners, int size) {
std::cout << "\n--- List of Car Owners ---\n";
for (int i = 0; i < size; ++i) {
std::cout << owners[i] << std::endl;
}
}
int main() {
int numberOfOwners;
std::cout << "Enter the number of car owners: ";
std::cin >> numberOfOwners;
// Dynamically allocate memory for an array of CarOwner objects
CarOwner* owners = new CarOwner[numberOfOwners];
// Read CarOwner details from the user and fill the dynamic array
for (int i = 0; i < numberOfOwners; ++i) {
std::cout << "Enter details for owner #" << (i + 1) << std::endl;
std::cin >> owners[i];
}
// Print the dynamic array of CarOwners
printCarOwners(owners, numberOfOwners);
// Don't forget to free the allocated memory
delete[] owners;
return 0;
}
This program:
Defines a CarOwner class with members name, age, and carModel.
Overloads the input operator (>>) to read CarOwner details from the console.
Overloads the output operator (<<) to print CarOwner details to the console.
Uses a function printCarOwners to iterate over and print each element of the dynamic array of CarOwners.
In the main function, it prompts the user to enter the number of car owners and their details, and then prints the entire list of owners.
Takes care to deallocate the dynamic array to prevent memory leaks.
Make sure you compile this program with a C++11 or later standard using a command such as g++ -std=c++11 program.cpp -o program, because the program uses the default constructor initializer list syntax, which is a feature introduced in C++11.