Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose a similar program were written in C# in which all the parameters were re

ID: 441891 • Letter: S

Question

Suppose a similar program were written in C# in which all the parameters were ref parameters. What would the output of that program be?

The output of the program will be value1 = 2 value2 = 2 value3 = 1

1. Examine the following C++ program, in which a wrapper Int class is defined that contains an overloaded += operator. What is the output of this program?

1. #include <iostream>

2. using namespace std;

3.

4. class Int

5. {

6. public:

7. Int(int value) {this->value = value;}

8. Int& operator+=(const Int& anInt)

9. {value += anInt.value; return *this;}

10. void doubleIt() {value *= 2;}

11. friend ostream& operator<<(ostream& out, const Int& anInt)

12. {return out << anInt.value;}

13. private:

14. int value;

15. };

16.

17. int main()

18. {

19. Int i(5), j(6);

20.

21. (i += j).doubleIt();

22. cout << i << endl;

23. return 0;

}

The output of the program is 22.

Notice that the overloaded += operator returns a reference. Change the += operator to return a value instead and determine what the output would be in that case. Explain the difference in behavior and why the ability to return by reference is essential to be able to implement such operators.

Explanation / Answer

17. int main()

18. {

19. Int i(5), j(6); // i=5, j=6

20.

21. (i += j).doubleIt();

// i+==j --> i= 5+6 = 11

//i.doubleIt --> i=11 *2 = 22

22. cout << i << endl;

23. return 0;

}


The += already returns a value. In general, the += is considered a short hand that adds the left hand operand to the right hand operand and saves the result in the left hand operand. If it did not return a value by reference, you may have to use i=i+j format instead, assuming the + is overloaded for this class


Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote