1) For every a and b which are non-const pointers of the same type, you can do a
ID: 658598 • Letter: 1
Question
1) For every a and b which are non-const pointers of the same type, you can do a = b;, right?
2) Inside non-const member functions the this keyword exists, which is a non-const pointer. So logicaly if b is same type as this you can also do this = b; right?
Wrong.
You cannot do this = b;, because this uses pointer syntax but logically this is a reference!
But why on earth is this syntactically a pointer but logically reference?
Can this weird behavior be corrected in next C++ standard, by introducing a new keyword, for example me which will be reference not only logically but also syntactically?
(See also my attempt to solve this here: Is it a good idea to
Explanation / Answer
this is (like nullptr) a constant pointer; the pointed data is const if and only if this appears in the body of a const member function.
You cannot change a constant pointer, like you cannot change a constant literal like 23.
So assignment to this like
this = p; // WRONG
is prohibited for the same reasons assignment to nullptr is forbidden:
nullptr = 0; // wrong
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.