Bear in mind that the evolution of the Catapillar and the butterfly are independant.
Natural selection of one does not affect the other. This process allows the same set of genes to function in different environments. As Mel satates all insects have a descrete larval stage so clearly at some point their common ancestor developed this trait, and since it allows better use of of the resources. It was clearly an advantage and has persisted, some highly social insects undergo their laval stage while still in the egg. This makes sense since if you think about it.
(pick up a few Richard Dawkins books on natural selection and that should give you a clear idea of what's happening)
What is weird to think though, is that inside the catapillar are a few cells that do nothing, but have been their since it hatched from it's egg... then when the catapilla enters its cacoon, these cells then secrete enzymes that digest the rest of the catapillar... and the butterfly grows from these cells which feed off the catapillar... weird huh!