C++ operator overloading with a default argument on operator+ (member): compute the result of objA + 5 and print it.\n\n#include <iostream.h>\n\nclass Addition\n{\n int x;\npublic:\n Addition() { x = 0; }\n Addition(int xx) { x = xx; }\n\n Addition operator+(int xx = 0)\n {\n Addition objTemp;\n objTemp.x = x + xx;\n return objTemp;\n }\n\n void Display() { cout << x << endl; }\n};\n\nint main()\n{\n Addition objA(15), objB;\n objB = objA + 5;\n objB.Display();\n return 0;\n}\n

Difficulty: Easy

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.

More Questions from Functions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion