C++ defaults, compound assignments, and parameter passing by value: trace member updates and print x and y.
#include
class CuriousTab
{
int x, y, z;
public:
void Apply(int xx = 12, int yy = 21, int zz = 9)
{
x = xx; // x = 12
y = yy += 10; // yy becomes 10 locally; y = 10
z = x -= 2; // x becomes 10; z = 10
}
void Display()
{
cout << x << " " << y << endl;
}
void SetValue(int xx, int yy)
{
Apply(xx, 0, yy); // pass-by-value
}
};
int main()
{
CuriousTab *pCuriousTab = new CuriousTab;
(*pCuriousTab).SetValue(12, 20);
pCuriousTab->Display();
delete pCuriousTab;
return 0;
}
-
A10 10
-
B12 10
-
C12 21
-
D12 31
-
EThe program will report compilation error.
Answer
Correct Answer: 10 10
Explanation
Introduction / Context: This exercise tests understanding of default arguments, pass-by-value, and chained assignments with compound operators. It asks you to follow exact state changes inside Apply and then print two members using Display.
Given Data / Assumptions:
- SetValue calls Apply(12, 0, 20).
- Parameters are passed by value; modifications to yy do not escape Apply except through explicit assignments to members.
- Operators used: yy += 10 and x -= 2, with their results assigned to y and z respectively.
Concept / Approach: Carefully evaluate compound assignments which both change the left-hand operand and yield a value. Keep track of x and y after each statement to determine what Display prints.
Step-by-Step Solution:
Entry to Apply: xx = 12, yy = 0, zz = 20.x = xx → x = 12.y = yy += 10 → yy becomes 10 (locally) and y receives 10.z = x -= 2 → x becomes 10 and z receives 10.Display prints x and y → "10 10".Verification / Alternative check: Rewriting as yy = yy + 10; y = yy; x = x - 2; z = x; confirms the same final member values.
Why Other Options Are Wrong:
- 12 10: Ignores the later x -= 2.
- 12 21 / 12 31: Misapply defaults or assume pass-by-reference, which is not used here.
- The program will report compilation error.: The code compiles as intended.
Common Pitfalls: Thinking yy += 10 returns the old value, or assuming parameters are references; both lead to incorrect y values.
Final Answer: 10 10