Four things are necessary for cavities to form --
A tooth,
Bacteria
Sugars or other carbohydrates and
Time
Dental plaque is a thin, sticky, colorless deposit of bacteria that constantly forms on everyone's teeth.
When you eat, the sugars in your food cause the bacteria in plaque to produce acids that attack the tooth enamel.
With time and repeated acid attacks, the enamel breaks down and a cavity forms.
Diet & oral hygiene are the main drivers of tooth decay. If you do not brush often and eat foods with high sugar contents you will be at more risk.