I want to understand why is it possible to return a reference to a class member variable in C++, such as in the following example:
class Foo
{
int x;
public:
int& get_pvar()
{
return x;
}};
Apparently we can access the variable x in main(), create a reference to it and then alter its contents:
Foo obj;
int& ref = obj.get_pvar();
ref = 7;
But how is this possible? x does not have global scope, neither is it a static member of the class. It is defined within the class. So, it should have local scope. So, why isn't it an error to return a reference to it and even create a reference to it in main()?