Reputation: 23
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;
};
Upvotes: 1
Views: 418
Reputation: 283634
There are a whole bunch of reasons to avoid the reference-typed data member:
If you really really want to expose a reference, do so as the return type of a member function:
const int& field() const { return field_; } // avoid leading underscores in application code
Generally though, a value return will be higher-performance and easier for the calling code to use.
Upvotes: 2