Examine the following C++ program, in which a IntList class is defined that cont
ID: 3562515 • Letter: E
Question
Examine the following C++ program, in which a IntList class is defined that contains an overloaded [] operator. What is the output of this program?
#include <iostream>
using namespace std;
class IntList
{
private:
int list[1];
public:
IntList() {list[0] = 0;}
int& operator[] (const int index) {return list[index];}
};
int main()
{
IntList list;
cout << list[0] << endl;
list[0] = 1;
cout << list[0] << endl;
return 0;
}
Notice that the overloaded [] operator returns a reference. Change the [] operator to return a value instead and explain what happens in that case. Explain why the ability to return by reference is essential to be able to implement such an operator. Can anything similar be done in Java?
Explanation / Answer
After changing the [] operator to return a value, you will get a compile error at the line of
list[0] = 1 in main method. This is because list[0] equals 1, so it
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.