Here is my code :
class X
{
public:
X():_x(5){}
void GetVal(int & oVal)
{
oVal = _x;
}
private:
int _x;
};
class Y
{
public:
X * const GetX()
{
return &_x;
}
private:
X _x;
};
int main()
{
Y y;
X * p = y.GetX();
int * pInt = new int[2];
p->GetVal(pInt[0]);
}
In the last line of main, I get an error
Incorrect access of a member from const-qualified function
This error is observed only when the code is compiled on a sun solaris system and doesn’t happen on windows or aix system. Any idea why?
Also the strangest thing is that the error is gone if I replace pInt[0], with a simple integer (int a = 0; p->GetVal(a))
The
constinX * const GetX()will be ignored, because the result of the function call is an rvalue and rvalues of non class type cannot beconstaccording to c++ const member function that returns a const pointer.. But what type of const is the returned pointer?.Are you sure you didn’t mean to write:
that is, you change it from returning a constant pointer to variable date into a variable pointer to constant data, and you declare
GetX()to be a constant member function, that is a member function that can be used on constant instances of Y:const Y y;Furthermore in
class X, you can changeGetVal()to