Practice mode C++

Assuming standard headers and using namespace std, what does this C++ code print? struct K { int n = 1; int get() const { return n; } int get() { return n + 10; } }; int main() { K a; const K b; cout << a.get() << ” ” << b.get(); }

Correct answer C. 11 1

Explanation

Member functions can be overloaded on const. For the non-const object a, the non-const get() is the better match and returns 11. For the const object b, only the const-qualified get() can be called, returning 1. This pattern is common in containers, where operator[] has const and non-const versions.

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.