And a more idiomatic example:
struct X {
X(Y val) : y_{val} {}
// Can be called on const and non-const X objects
const Y& y() const { return y_; }
// Can only be called on non-const X objects
Y& y() { return y_; }
private:
Y y_;
};
void f(X& x) { x.y() = 222; }
void g(const X& x) { x.y() = 222); }
const X x{123}; // x.y() == 123
x.y() = 222; // compilation error
f(x); // compilation error (f's parm is non-const)
g(x); // compilation error (can't assign to const ref)
// Cannot take non-const ref or ptr of x
X& xr{x}; // compilation error
X* xp{&x}; // compilation error
If the original declaration of the variable is const nothing can modify it. (And as my first example shows, the original declaration can always be const if you want it to be, regardless of context.) You can't take a non-const pointer or reference to x without explicitly circumventing the language like this:
X& xr{const_cast<X&>(x)};
X* xp(const_cast<X*>(&x)};