Write a program which will use a class named Product. The Product class will hav
ID: 3936022 • Letter: W
Question
Write a program which will use a class named Product. The Product class will have data values for name (string) and price (double). It will have functions to do the following:
· Construct a new instance of the Product class
· Assign a value to the name
· Assign a value to the price
· Return the value of the name
· Return the value of the price
You will have to write the interface and the functions listed in the interface.
The main program will do the following:
· It will declare first_product and second_product as pointers to instances of Product.
· It will use the constructor to create new instances of Product and set first_product and second_product to each point to an instance of Product.
· Get values of name and price and assign them to the data values of first_product.
· Get values of name and price and assign them to the data values of second_product.
· Dereference first_product and print the values of its name and price.
· Dereference second_product and print the values of its name and price.
· Delete first_product.
· Delete second_product.
Explanation / Answer
Assuming that the required programming language is C++
#include <iostream>
using namespace std;
class Product{
string name;
double price;
public:
Product( string nm="", double prc=0 ){
name = nm;
price = prc; }
void setName( string nm ){
name = nm; }
void setPrice( double prc ){
price = prc;
}
string getName(){
return name;
}
double getPrice(){
return price;
}
};
int main(){
Product* first_product, *second_product;
first_product = new Product();
second_product = new Product();
string name;
double price;
cout << "Enter name of first product: ";
cin >> name;
cout << "Enter price of first product: ";
cin >> price;
first_product->setName( name );
first_product->setPrice( price );
cout << "Enter name of second product: ";
cin >> name;
cout << "Enter price of second product: ";
cin >> price;
second_product->setName( name );
second_product->setPrice( price );
cout << endl << endl;
cout << "First Product: " << endl;
cout << "Name: " << (*first_product).getName() << endl;
cout << "Price: " << (*first_product).getPrice() << endl;
cout << endl;
cout << "Second Product: " << endl;
cout << "Name: " << (*second_product).getName() << endl;
cout << "Price: " << (*second_product).getPrice() << endl;
cout << endl;
delete first_product;
delete second_product;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.