Being private means that you cannot access Ref::x. It doesn't mean that the class controls what you can do with other references you might have to its members.
If you have access to the referenced variable (z), you can change it, if you only have an instance of Ref, you can't.
Consider this:
Code:
#include <iostream>
class Ref
{
private:
int & x;
public:
Ref(int & a);
~Ref();
void show() {std::cout<< x << std::endl;};
};
Ref::Ref( int & a): x(a)
{ }
Ref::~Ref()
{}
void show(const Ref& ref)
{
//in this function you have no access to the reference
ref.show();
}
int main()
{
int z = 4;
Ref y = Ref(z);
show(y);
z = 5;
show(y);
return 0;
}
In principle it is quite similar to having const and nonconst references to a value. If you have a const reference to something, it means you can't use this reference to modify the value. If you also have nonconstant references to the same value, you can modify it using those.
Code:
#include <iostream>
int main()
{
int z = 10;
const int& ref = z;
std::cout << ref << '\n';
//ref = 20; //not allowed
z = 20; //fine
std::cout << ref << '\n';
}
I've only seen reference members used a few times and each time they confused me to no end. Something about seeing the ampersand in a class declaration just makes my brain go awry. There are reasons for doing it but I do not remember what they are.
A reference member means that by default the class will be copyable but not assignable, which is a rather unusual combination. If both are wanted, a pointer member allows that.