"Cavity" means tooth decay, and in medical terminology it is called dental caries. Dental caries or cavities are caused by erosion of tooth enamel by the acids present in the mouth. The bacteria present in the mouth get deposited (along with saliva, food particles and other natural substances) on the surface of the teeth. This is called plaque. The bacteria in the plaque convert the sugar and carbohydrates present in the foods we eat into acids. These acids cause erosion of tooth enamel that leads to cavity.
Cavity can be caused anywhere on the tooth which is exposed to plaque and acid, like the hard outer enamel on the tooth crown or the root of the tooth that lacks enamel (which is exposed by gum recession). Caries can extend from the enamel to the dentin (main body of the tooth) or even up to the soft tooth pulp and the sensitive nerve fibres within it. What causes pain in cavity is not known. Pain is probably caused by inflammation due to bacteria, exposure of root of the tooth and an imbalance of fluid levels in the dentin.