c++member-access

Can I assign to the return value of member access operator?


I've read that the Member Access Operators dot operator . and arrow operator -> return values:

The arrow operator requires a pointer operand and yields an lvalue. The dot operator yields an lvalue if the object from which the member is fetched is an lvalue; otherwise the result is an rvalue.

This is from C++ Primer 5 edition.

So I imagine I can assign a value whenever a non-const lvalue is the return of their expression e.g:

struct foo {
    int x_;
    const int y_ = 17; ;
    void bar() { cout << "bar()" << endl;}
}f, *pf;

pf = &f;

(pf->bar()) = 75; // error
cout << f.x_ << endl;
(f.bar()) = 12;// error
(f.x_) = 23;
cout << "f_x: " << f.x_ << endl;
(pf->y_) = 34;// error

I am confused about assigning to the return value of arrow operator. Above it is said that -> always returns an lvalue but it fails if I try to assign to that value.


Solution

  • Above it is said that -> always returns an lvalue but it fails if I try to assign to that value.

    This is about member variables, not functions. bar returns void so you can never assign to it. x_ works since it gives you an integer lvalue expression. y_ fails because it is const, and you can't assign to a const variable.

    So, in

    foo bar;
    foo* f = &bar;
    f->x_;
    f->y_;
    

    both member accesses yield an lvalue expression. In

    foo f;
    f.x_;
    f.y_;
    

    you again have lvalues since f is an lvalue. However, in

    foo{}.x_;
    foo{}.y_;
    

    both member accesses are rvalues since foo{} is an rvalue.