c++classscopemember-variablesreturn-by-reference

How come we can return references to member variables of a class


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()?


Solution

  • You are confusing scope and lifetime. Those are two related, but ultimately different concepts.

    The scope of the name x is the class scope. You can only use the unqualified name x for the member inside members functions (and some other minutia, irrelevant here) of the class.

    The lifetime of the member object named x is the same as the enclosing class object. In this case, the lifetime of obj.x is the same as obj. Since you return a reference to an object within its lifetime, everything checks out.


    The reason for your confusion may stem from learning that objects with automatic storage duration, like the following:

    {
        int x;
    }
    

    Have their lifetime bound to their lexical scope (they can only be named inside those curly braces, their scope). But while it's true for those objects, it is not something that holds in general. Class objects can live independently of the scope of their name (as you saw). And some objects can have a lifetime but no scope and name. Consider:

    auto* p = new Foo();
    

    The new expression creates an object, but it has no name! So there is no scope to even speak of. Here p is the name of a pointer, not of the newly created object.