Bogdan Mihai
Bogdan Mihai

Reputation: 283

friend function returning reference to private data member

I have two questions about the following code.

class cls{
    int vi;
    public:
        cls(int v=37) { vi=v; }
        friend int& f(cls);
};

int& f(cls c) { return c.vi; }

int main(){
    const cls d(15);
    f(d)=8;
    cout<<f(d);
    return 0;
}
  1. Why does it compile, since f(d) = 8 attemps to modify a const object?
  2. Why does it still print 15, even after removing the const attribute?

Upvotes: 0

Views: 261

Answers (1)

hmjd
hmjd

Reputation: 122001

It is not modifying a const object as a copy of d is being made due to the argument of f() being passed by value and not by reference. This is also the reason that d is unchanged as it is not being modified.

Upvotes: 6

Related Questions