Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading