Many of the genes responsible for the virulence of bacterial pathogens are carried by mobile genetic elements that can be transferred horizontally between different bacterial lineages. Horizontal transfer of virulence–factor genes has played a profound role in the evolution of bacterial pathogens, but it is poorly understood why these genes are so often mobile. Here, I present a hypothetical selective mechanism maintaining virulence–factor genes on horizontally transmissible genetic elements. For virulence factors that are secreted extracellularly, selection within hosts may favour mutant ‘cheater’ strains of the pathogen that do not produce the virulence factor themselves but still benefit from factors produced by other members of the pathogen population within a host. Using simple mathematical models, I show that if this occurs then selection for infectious transmission between hosts favours pathogen strains that can reintroduce functional copies of virulence–factor genes into cheaters via horizontal transfer, forcing them to produce the virulence factor. Horizontal gene transfer is thus a novel mechanism for the evolution of cooperation. I discuss predictions of this hypothesis that can be tested empirically and its implications for the evolution of pathogen virulence.