Let's say we have a class X that holds a pointer to an object of class Y. X never changes Y in any way, but other objects which might want to change Y can ask X for a pointer to Y. We want class X to be able to hold both const and variable objects. If we write something like this:
class Y;
class X {
public:
const Y* getY();
private:
const Y* y;
};
then we could never alter Y when getting it from X, even when the original "Y object" is not const.
An example where this would be useful is a linked list that holds both const and variable objects.
How would one go about implementing this?
Yinstance is mutable (guaranteed by forces above your head) return a non-constY *andconst_castaway theconstin the getter. C++ always gives you the opportunity to do something stupid when there's a chance that it might not be stupid under controlled circumstances. 's why we still have widely reviled stuff likegoto.gotohas been castrated, since you can't dovoid foo() { goto yonder; } void bar() { yonder: cout << "We're here!\n"; }We've got structured goto, that's been tamed, constrained, and detained, rather than proper yeehaw goto that can rampage hither-and-yon. Assembly language programming, for the win!Yis mutable, casting awayconstis not a good solution. But if you have a wrapper around it that can tell you if it's mutable or not you have the ability to say "Oh hell no!" if someone asks for a non-constpointer. Saying "No" may or may not be viable in your use case, but perhaps you can move the abstraction elsewhere.