Search code examples
c++rvaluelvalue

Getter returns a rvalue?


I know it's a bad attempt but why we cannot edit the private member via the getter?

class A
{
    int a = 2;
public:
    int GetA1() { return a; }
    int& GetA2() { return a; }
    int* GetA3() { return &a; }
};
int main() {
    A test;
    test.GetA1() = 4;     

    test.GetA2() = 4;     
    int b = test.GetA2(); 

    int* pb = &b;
    test.GetA3() = pb;
}

I think GetA1() doesn't work because it's using a rvalue, the copy by return. But then I'm a little surprised that GetA2() can work and at last really confused that GetA3() cannot work.

It seems that the value on member's address can be changed, but the address itself not. Does GetA3 returns a rvalue or an unmodifiable lvalue?

Thanks!


Solution

  • It seems that the value on member's address can be changed, but the address itself not.

    Indeed. More generally, it isn't possible to change the address where any object is stored. This applies to all objects.

    Does GetA3 returns a rvalue or an unmodifiable lvalue?

    GetA3() is an rvalue, more specifically it is a prvalue (just like GetA1() is also a prvalue). The type of the prvalue is "pointer to int" (unlike the type of GetA1() which is just int).