Examine the following C++ program: Notice that the overloaded [] operator return
ID: 3558893 • Letter: E
Question
Examine the following C++ program:
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?
#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;
}
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.