I have a class with a private field. This field is written only inside the class, but must be readable from outside. Which option is preferable and why? First, with const reference
class Test {
public:
const int &field; // can read outside
inline Test() noexcept: field(_field) {}
void someMethod() {
_field = 123; // writing occurs only inside the class
}
private:
int _field;
};
Or second, with inline getter:
class Test {
public:
void someMethod() {
_field = 123; // writing occurs only inside the class
}
inline int field() const noexcept { // can call outside
return _field;
}
private:
int _field;
};