I have these code
#include <iostream>
using namespace std;
class Ex;
class Exx;
class Ex {
public:
int _val;
int const *_p_val;
void setPtrVal(int * const &val) {
_p_val=val;
}
};
class Exx {
public:
Ex const *_ex;
void setEx(Ex const &ex)
{
_ex=&ex;
}
};
int main()
{
Ex x;
int i=10;
x.setPtrVal(&i);
Exx xx;
xx.setEx(x);
int y=20;
cout<<*(xx._ex->_p_val)<<endl;
x.setPtrVal(&y);
cout<<*(xx._ex->_p_val)<<endl;
cout<<*x._p_val<<endl;
return 0;
}
1: you can see, Ex x is not a const of Ex class. And Ex const *_ex; is a pointer point to only Ex const. why everything above are ok?
2: Is const in void setEx(Ex const &ex) just means you can't modify ex in function body?
3: how fix setter function for member pointer variable if I want prototype like above (suppose for sercurity reason)?
OK. if Ex const *_ex; become Ex *_ex; So, in setter function, I want a prototype do not modify argument object, just like above. How function body become?
A pointer (or reference) to
const
does not have to point to aconst
object. It just means that it can't be used to modify the object it points to; so it can safely point to either aconst
or non-const
object.Yes. Specifically, it means that the reference passed as the function argument can't be used to modify the object.
It's better to include
const
if you don't need to use it for modification. That will prevent accidental modification, and allow you to point toconst
objects.