Why is it impossible to convert const X to X &?

c++, constants, reference

Solution

Why is it impossible to convert `const X` to `X &`?

Because if it is allowed, the following dangerous code becomes valid:

const int x = 0;
int& rx = x;     // bind const variable to reference (to non-const)
rx = 99;         // oops, try to modify the const variable via the reference

What should I do to correct this? Should I leave `getRotationCenter` without `const` ?

It depends on your intent. If the returned object could be modified, then make the member function non-const and return `Point&`. If not, then leave the member function `const` and make the return type `const Point&`. A const member function means a promise that won't modify (or provide the possibility to modify) the object (and its members).

Problem

I'm trying to understand and achieve const correctness on a Tetris Project. Here is a recurrent problem that i have when i'm trying to add const where I think it's necessary. I have a (Piece) class, and one of it's class private member is ``` Point rotationCenter; ``` And I'm trying to write a getter like this: ``` inline Point & Piece::getRotationCenter() const { return rotationCenter; } ``` Before, I had the same getter, but not as a const function, and was working. Now, I got the C2240 error "impossible to convert const Point to Point &". What should I do to correct this? Should I leave `getRotationCenter` without `const` ? PS : I read https://isocpp.org/wiki/faq/const-correctness as tutorial.

Original source