QUESTION 3 - WALKTHROUGH - (20 MARKS): What is the exact output of the following
ID: 3818544 • Letter: Q
Question
QUESTION 3 - WALKTHROUGH - (20 MARKS): What is the exact output of the following program? Show your rough work to avoid deductions. #include using namespace std; class Fruit { int items; double price; public: Fruit(); Fruit(int, double); Fruit(const Fruit&); void to(Fruit&); void operator+=(double); friend ostream& operator<<(ostream&, const Fruit&); virtual ~Fruit(); }; Fruit::Fruit() { items = 0; price = 0.0; cout << '#'; } Fruit::Fruit(int i, double p) { items = i; price = p; cout << '!'; } Fruit::Fruit(const Fruit& f) { items = f.items; price = f.price; cout << '$'; } void Fruit::to(Fruit& dest) { if (items > 0) { dest.items++; items--; } } void Fruit::operator+=(double change) { price += change; } Fruit::~Fruit() { cout << '~' << *this << endl; } ostream& operator<<(ostream& os, const Fruit& s) { os << s.items << '-' << s.price; return os; } class OldFruit : public Fruit { public: OldFruit (); OldFruit (int, double); OldFruit (const OldFruit&); friend ostream& operator<<(ostream&, const OldFruit&); ~OldFruit(); }; OldFruit::OldFruit () { cout << '&'; } OldFruit::OldFruit (int i, double p) : Fruit(i, p) { cout << ':'; } OldFruit::OldFruit(const OldFruit& f) : Fruit(f) { cout << '*' << endl; } OldFruit::~OldFruit() { cout << '%' << *this << endl; } ostream& operator<<(ostream& os, const OldFruit& s) { os << (Fruit&)s; // calls Fruit version of << operator os << " reduced "; return os; } OldFruit reduce(Fruit& fruit, int n, double p) { OldFruit old; for (int i = 0; i < n; i++) fruit.to(old); old += p; return old; } int main() { Fruit apples(5, 2.00), pears; cout << endl; cout << '=' << apples << endl; OldFruit oldApps = reduce(apples, 2, 1.00); cout << '=' << oldApps << endl; return 0; }
Explanation / Answer
Output of this will be
!#
=5-2
#&=2-1
%2-1
~2-1
~0-0
~3-2
In this first contructor for apples is printing, then constructor for pear (paramterised and non paramterised contructor)
then cout endl
then cout = and then call to friend operator << is printing
and so on.
At last destructors are being called.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.