The reason why this fails is that inside a const
member function, this
is really a const Point*
, not a Point*
. Thus you are trying to initialize a non-const
reference from a const
pointer. It's not that the compiler isn't believing you, you're just asking for two incompatible things at one time.
This is one of the very few valid uses of const_cast
, in my opinion. Normally, using const_cast
is almost always a sign of a design error, or worse a programming error.
Here, the function is really const
and should be const
, but there is no reason why you shouldn't be able to chain something non-const
afterwards, so it's arguably legitimate to do such a thing.
Do note, however, although the function is strictly const
(in respect to the object, not so much in its use of IO functions!), one thing you should consider is that in some (rare) cases, it may result in code that doesn't do what you want. The compiler is allowed to cache the result of a const
function and omit another call to the same const
function (since you promised that it won't change anything). Therefore, it is allowable to optimize some_point.Print().Print();
into some_point.Print()
. This is probably not a problem for you (why would you want to print the same values twice), just something to be generally aware of.