C++ operator overloading with a default argument on operator+ (member): compute the result of objA + 5 and print it.
#include
class Addition
{
int x;
public:
Addition() { x = 0; }
Addition(int xx) { x = xx; }
Addition operator+(int xx = 0)
{
Addition objTemp;
objTemp.x = x + xx;
return objTemp;
}
void Display() { cout << x << endl; }
};
int main()
{
Addition objA(15), objB;
objB = objA + 5;
objB.Display();
return 0;
}
-
AThe program will print the output 20.
-
BThe program will report run time error.
-
CThe program will print the garbage value.
-
DCompilation fails due to operator + cannot have default arguments.
-
ENone of the above
Answer
Correct Answer: The program will print the output 20.
Explanation
Introduction / Context: This question validates understanding of member operator overloading and default arguments. A member operator+(int) computes a new Addition whose x is the receiver’s x plus the provided integer. Default arguments on operators are allowed in C++ and are not the cause of any compilation issue here.
Given Data / Assumptions:
- objA is constructed with x = 15.
- Expression objA + 5 invokes Addition::operator+(int).
- The operator returns a new Addition with x = 15 + 5 = 20, then Display prints that value.
Concept / Approach: Member operator+(int) is analogous to a method call objA.operator+(5). It builds a temporary result object with the sum and returns it by value. No undefined behavior occurs; the temporary is copied into objB.
Step-by-Step Solution:
Construct objA with x = 15; objB with default x = 0.Invoke objA + 5 → creates objTemp with x = 20.Assign objTemp to objB (copy elision may apply) → objB.x = 20.objB.Display() prints 20.Verification / Alternative check: If you omit the argument (objA + ), the default argument 0 would be used and the result would be 15. The code as written provides 5 explicitly.
Why Other Options Are Wrong:
- Run time error / garbage: nothing invalid or uninitialized occurs.
- Compilation fails due to operator + cannot have default arguments.: False; operators may have default parameters like any function, subject to signature rules.
Common Pitfalls: Confusing member versus non-member operator overload constraints, or assuming default arguments are disallowed for overloaded operators.
Final Answer: The program will print the output 20.