flies eventually learn to spot mated females, but just how they do has remained a mystery.
Research published in Nature suggests that they smell a chemical signal called a pheromone left by other males during mating.
The studies were performed using the common fruit fly - Drosophila melanogaster.
This insect is used widely in genetic studies because they are easy to grow and they reproduce quickly - but principally because it is possible to generate and study flies that possess changes - or mutations - in their genetic material.
In the study, Prof Barry Dickson and colleagues from the Research Institute of Molecular Pathology in Vienna, Austria, performed a series of studies to identify the mechanism that led to this change in behaviour in older flies.
Using complementary approaches, the team showed that a pheromone called cVA was responsible.
Pheromones are substances produced by one individual which modify the behaviour of another.
They are widely known to work in the animal kingdom to warn of danger, define territories or attract mates.
In male fruitflies, cVA is deposited on females during mating in what appears to be another example of signalling.
In one experiment, the team showed that male fruitflies that could not sense cVA, either because of a natural mutation or genetic engineering, could not differentiate between mated and virgin females.
In another, females engineered to produce the pheromone kept the amorous males at bay, even though the females had not mated.
From the outset, male flies can smell cVA but do not respond to it.
However, they soon learn to associate courtship rejection with the presence of the pheromone.
This learning process is mediated by a powerful chemical - called dopamine - released by their primitive brains.
In insects, dopamine affects a range of behaviours including sleep, movement, courtship and learning.
In mammals, it affects the brain and is associated with reward.
Drugs such as cocaine cause release of large amounts of dopamine.
Discussing the implications of the research, Prof Dickson said: “Similar learning strategies are likely to apply across a wide range of species, including humans, and indeed there is considerable evidence that dopamine signals mediate learning in a wide variety of contexts and species.”