To understand how a cavity works, we need to have a basic understanding of the anatomy of the tooth. A tooth is composed of several layers. The outermost layer (above the gum line) is called the enamel. Enamel is the hardest and most mineralized substance in the body. Beneath the gum line, a substance called cementum covers the tooth roots. Under the enamel and cementum is the dentin. The dentin is about as hard as bone, and, unlike the enamel, dentin contains nerve endings. Beneath the dentin is the dental pulp. The pulp is a vascular tissue composed of capillaries, larger blood vessels, connective tissue, nerve fibers, and cells including odontoblasts, fibroblasts, macrophages and lymphocytes. The pulp is needed to nourish the tooth during its growth and development. After a tooth is fully mature, the only function of the pulp is to let us know if it is damaged or infected by transmitting pain.
Source: http://www.dentistry.com/