0

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;
}

...

  • `const YPTR` is `Y * const` not `const Y *` as might be expected by an intuitive substitution. – François Andrieux Nov 21 '21 at 16:49
  • `const YPTR` is `Y* const`, not `const Y*`. The first is const pointer to non-const data, the second is non-const pointer to const data. You can assign `y1ptr`, because it is a copy of the returned const pointer. You cannot assing `y2ptr` because pointer to const and pointer to non-const are 2 different types. – Yksisarvinen Nov 21 '21 at 16:49

0 Answers0