Practice mode C++

Assuming standard headers and using namespace std, what does this C++ code print? struct C { int v = 0; C& operator++() { v += 10; return *this; } C operator++(int) { C t = *this; v += 1; return t; } }; int main() { C c; ++c; c++; cout << c.v; }

Correct answer D. 11

Explanation

++c calls the prefix overload, operator++(), adding 10. c++ calls the postfix overload, which is distinguished by its dummy int parameter, adding 1. The total is 11. By convention the prefix form returns a reference to the updated object while the postfix form returns a copy of the old value, which is why prefix is often cheaper.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.