Sometimes a caterpillar eats eggs, another caterpillar, a pre-pupa, or a chrysalis, even when there is enough food. Why?
When we stop to think about it, we realize that an caterpillar is simply a mature egg plus host plant. A pre-pupa is addition of time and more host plant. A chrysalis is the addition of … you get the idea.
Because a caterpillar, pre-pupa, and chrysalis are made entirely of the host plant, so to speak, the taste of the insect would be tasty to caterpillars that eat the same host plant, whether they are the same species or not. We know that some caterpillars that eat distasteful plants are distasteful to many predators. The taste of the host plant controls the taste of the insect.
The instinct of some species of caterpillars, when they hatch, is to eat its egg shell. Once that shell is eaten, if there is another egg nearby, that instinct may cause it to continue eating eggs.
Although it happens more often when caterpillars are contained and run out of food, cannibalism happens even when there is plenty of food available.
Cloudless sulphur caterpillars are well known for cannibalism, out in nature. Even on a large host plant, they often attack and eat other caterpillars. They are one species that are often raised separately, one per plant stem.
Pipevine swallowtails and gold rim (polydamas) swallowtails are extremely cannibalistic in captivity. Once they are near pupation, many farmers raise them separately. As young caterpillars, they are gregarious, staying together on a leaf. Once they grow to three or four instars, they naturally separate on the plant.
To be safe, simply make sure they have plenty of food and learn which species tend to cannibalize in captivity. Separate them at the appropriate age.