1- Explain what the operator Box& operator+=(const Chocolate& c) does. 2- How can you improve the performance the show() function in this program. Explain the effect of your upgrade in one or two sentences. 3- Explain in one or two sentences the meaning of the keyword const in the display()function. 4- Describe in one or two sentences the effect of removing the default parameter value in the definition of the Chocolate() constructor.
Consider the following code. Answer questions 1 to 4. This is a walkthrough question
#include <iostream>
#include <cstring>
using namespace std;
const int NT = 10;
const int NC = 2;
class Chocolate {
char type[NT + 1];
public:
Chocolate(const char* t = nullptr) {
if (t) {
strncpy(type, t, NT);
type[NT] = '\0';
}
else {
type[0] = '\0';
}
cout << "C";
}
~Chocolate() {
cout << "~" << type << endl;
}
void display() const {
cout << type << endl;
}
};
class Box {
Chocolate ch[NC];
int nc;
public:
Box() {
nc = 0;
cout << "B";
}
Box& operator+=(const Chocolate& c) {
if (nc < NC) {
ch[nc] = c;
cout << "+";
ch[nc++].display();
}
return *this;
}
Box(const Box& b) {
nc = b.nc;
for (int i = 0; i < nc; i++)
ch[i] = b.ch[i];
cout << "E" << endl;
}
~Box() {
cout << "~B" << endl;
}
void display() const {
for (int i = 0; i < nc; i++)
ch[i].display();
cout << endl;
}
};
void show(const Box b) {
b.display();
}
int main() {
cout << "=Chocolate=" << endl;
Chocolate cherry("cherry");
Chocolate orange("orange");
cout << "\n=Box=" << endl;
Box b;
cout << "\n=++=" << endl;
b += orange;
b += cherry;
cout << "\n=show=" << endl;
show(b);
cout << "\n=done=" << endl;
return 0;
}
1- Explain what the operator Box& operator+=(const Chocolate& c) does.
2- How can you improve the performance the show() function in this program. Explain the effect of your upgrade in one or two sentences.
3- Explain in one or two sentences the meaning of the keyword const in the display()function.
4- Describe in one or two sentences the effect of removing the default parameter value in the definition of the Chocolate() constructor.
Step by step
Solved in 3 steps