I have following code:
struct MyStruct {
int a;
int b;
};
class Foo {
public:
MyStruct const &getValue() {
return value;
}
private:
MyStruct value{10, 20};
};
int main() {
Foo foo{};
auto v = foo.getValue();
v.a = 42; // compiles! it shouldn't!
}
I want to return a reference to private member, but don't allow caller to mutate contents of this reference. Just declaring return type to be MyStruct const & is not enough, as it probably defines the reference itself to be const, not the object reference points to. Though, declaring return type as MyStruct& const fails with "'const' qualifier may not be applied to a reference". I believe I might be missing something here.
I could have solved that with declaring MyStruct with all const fields, but I want to mutate it myself inside my class — only disallow caller to do so.
How is it possible to do so?