I need to store an array of newspapers and booklets And then in a loop, print out how much paper it takes to print each product, but when I call the price calculation function, the function is called from the main class and not from the child ones, how can I call the function from the child classes in an array with different objects?
#include <iostream>
using namespace std;
class PrintedProduct
{
public:
string name;
int pages;
int paperCost()
{
return 1;
}
PrintedProduct() {}
PrintedProduct(string name, int pages)
{
this->name = name;
this->pages = pages;
}
};
class NewsPaper : public PrintedProduct
{
public:
int pageSize;
int quantity;
int period;
NewsPaper(string name, int pages, int pageSize, int quantity, int period) : PrintedProduct(name, pages)
{
this->pageSize = pageSize;
this->quantity = quantity;
this->period = period;
}
int paperCost()
{
return pages * pageSize * quantity * period;
}
};
class Booklet : public PrintedProduct
{
public:
int pageSize;
int quantity;
Booklet(string name, int pages, int pageSize, int quantity)
: PrintedProduct(name, pages)
{
this->pageSize = pageSize;
this->quantity = quantity;
}
int paperCost()
{
return pages * pageSize * quantity;
}
};
void print(PrintedProduct a)
{
cout << a.paperCost() << endl;
};
int main()
{
// Write C++ code here
size_t size;
cout << "Please, enter a size of the array: " << endl;
cin >> size;
PrintedProduct *array = new PrintedProduct[size];
cout
<< "Please, enter "
<< size
<< " Printed products: ";
for (size_t i = 0; i < size; i++)
{
cout << "Please enter: 1. Newspaper or 2. Booklet";
int type;
cin >> type;
if (type == 1)
{
cout << "Enter name:" << endl;
string name;
cin >> name;
cout << "Enter page count" << endl;
int pages;
cin >> pages;
cout << "Enter page size " << endl;
int pageSize;
cin >> pageSize;
cout << "Enter quantity" << endl;
int quantity;
cin >> quantity;
cout << "Enter period" << endl;
int period;
cin >> period;
array[i] = NewsPaper(name, pages, pageSize, quantity, period);
}
else
{
cout << "Enter name:";
string name;
cin >> name;
cout << "Enter page count";
int pages;
cin >> pages;
cout << "Enter page size";
int pageSize;
cin >> pageSize;
cout << "Enter quantity";
int quantity;
cin >> quantity;
array[i] = Booklet(name, pages, pageSize, quantity);
}
}
for (size_t j = 0; j < size; j++)
{
print(array[j]);
}
delete[] array;
std::system("PAUSE");
return EXIT_SUCCESS;
}