Is it good to use a const reference field as a readonly getter in C++ classes?
I mean, does this code meet good practices?
class check{
private:
int _x;
public:
const int& x = _x;
void setX(int v){
_x = v;
}
};
It is working very much like C# properties, IMHO, and very easy and clean in class usage code:
check s;
int i;
std::cin >> i;
s.setX(i);
std::cout << s.x << '\n';
s.setX(7);
// s.x = i; // Error
std::cout<<s.x<<'\n';
Generally, it is not a good practice.
Why should that be clearer and easier?
The "classic" approach is sound clearer by me, e.g.:
From a performances point of view, this approach should be preferred.
get_variable
on an inline function does not introduce more overhead than your "reference approach". Moreover, it is highly optimizable by the compiler (because of straightforward of the code).