Reputation: 22823
How this code modifies a value in a const function:
#include<iostream>
using namespace std;
class Y;
class X{
public:
void access(Y &y) const;
};
class Y{
int d;
public:
friend void X::access(Y &y) const;
Y(){d=0;}
};
void X::access(Y &y) const
{
cout<<"Y is "<<y.d<<endl;
y.d=1;
cout<<"Y is "<<y.d<<endl;
}
int main() {
X x;
Y y;
x.access(y);
}
And this code gives an error:
#include<iostream>
using namespace std;
class Y{
int d;
public:
void set() const{d=0;}
};
int main() {
Y y1;
return 0;
}
Upvotes: 1
Views: 5920
Reputation: 340188
Because in your first example:
void X::access(Y &y) const;
the const
tells the compiler that the function won't modify the class X
object that the implicit this
parameter points to. The class Y
object that's passed as a reference isn't const
.
In the second example, the set()
function is a member of class Y
:
void set() const
and it's declared such that the implicit this
parameter pointing to the Y object is a const pointer (so that object can't be modified).
If you want X::access()
to not be permitted to modify the Y
object passed to it, change the declaration to:
void X::access(Y const& y) const;
Upvotes: 4
Reputation: 35901
a member function being const only promises not to change any members of the class it belongs to (execpt if they are declared mutable).
In the first example, Y.d is being modified in method X::access. The method does not modify any members of X itself so is perfectly sane.
In the second example however, the Y::set() method is declared const so it cannot change Y::d.
Next time, please post the code here instead of providing a link.
Upvotes: 2
Reputation: 355039
In the first example, the const-qualifier on X::access(Y &y) const
means that the X
object on which it is called cannot be modified. Since the Y
parameter is taken by non-const reference, it can be modified from within the function.
In the second example, the const-qualifier on Y::set() const
means that the Y
object on which it is called cannot be modified, hence why you cannot modify the non-mutable member variable d
.
Upvotes: 2
Reputation: 263118
Because inside a const
function, only *this
is const
, not the parameters passed to the function or anything else.
Upvotes: 3