It doesn't. The altimeter is simply a barometer. It reads air pressure and expresses it as a height / altitude / flight level depending on the pressure set on subscale.
It has no idea it's doing this, of course. We have simply designated that if you set the sub scale to a value that will have the instrument reading zero on the ground, it is measuring height above that point on the ground (QFE).
If we set it so it reads (approximated) height above sea level (so it'd read zero at sea level) it is measuring altitude (Regional QNH).
If we set the subscale to 1013.3mb (fruit pastilles these days) it will measure flight level (FL).