CPA-21-02 practice question 29 of 35

What will happen when you attempt to compile and run the following code? #include #include using namespace std; string fun(string, string); int main() { string s="Hello"; cout

Full set: 257 questions
Answer options
A: It will print: Hello World Correct answer
B: It will print: Hello
C: It will print: World
D: It will print: HW
Correct Answer:
A. It will print: Hello World
Explanation

The program defines a function fun that takes two std::string arguments and returns their concatenation using the overloaded operator+. In the main function, fun is called with a std::string variable ("Hello") and a string literal (" World"). The string literal is implicitly converted to a std::string object. The function concatenates these two strings and returns the combined string "Hello World", which is then printed to the standard output stream by cout.

Why Incorrect

B: Incorrect because the function concatenates both strings; it does not just return the first argument. C: Incorrect because the function does not ignore the first argument to return only the second string. D: Incorrect because operator+ for std::string concatenates the full contents of the strings, not just their initial characters.

References

1. ISO/IEC 14882:2017 Standard, Section 24.3.2.6 [string.op.plus] (operator+ for basicstring).

2. Bjarne Stroustrup, "The C++ Programming Language", 4th Edition, Chapter 36 (Strings).

Scroll to Top