I have the following code (very simplified version of actual code) that returns a const pointer in two ways, one as "const Y *" and one as "const YPTR" where "typedef Y * YPTR". The "const Y *" works as expected, where the compiler (linux, g++, version 10.1.0) does not allow me to assign it to a non constant variable. However, the compiler accepts the statement "Y * y1ptr = x.Y1ptr()". Why? Is this a quirk of the compiler?
...
#include <iostream>
class Y {
public:
int val;
};
typedef Y * YPTR;
class X {
public:
Y * y1;
Y * y2;
const YPTR Y1ptr() const
{ return y1; }
const Y * Y2ptr() const
{ return y2; }
};
int main()
{
using namespace std;
X x;
Y y1, y2;
y1.val = 100;
y2.val = 200;
x.y1 = &y1;
x.y2 = &y2;
Y * y1ptr = x.Y1ptr();
Y * y2ptr = x.Y2ptr();
y1ptr->val = y1ptr->val+2;
y2ptr->val = y2ptr->val+2;
cout << "y1ptr->val: " << y1ptr->val << endl;
cout << "y2ptr->val: " << y2ptr->val << endl;
}
...