What is the output of the following piece of code and why?
#include <iostream>
class A {
public:
int value() { return 1; }
int value() const { return 2; }
};
int main() {
A a;
const auto b = a.value();
std::cout << b << '\n';
}Show answer and explanation
The output is 1. Overload resolution uses the cv-qualification of object a, which is non-const, so it calls the non-const member; the const on result variable b does not affect that earlier call.
The output is 1. Overload resolution uses the cv-qualification of object a, which is non-const, so it calls the non-const member; the const on result variable b does not affect that earlier call.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.