I think it's an understanding that is built through experience.
A child with little experience may choose to behave one way, thinking it is good to do so, but will later come to realize that they were not doing the good they thought they were. As we grow and gain experiences, our understanding of how to bring about favorable moral outcomes grows, such that we may actually appear immoral to people who do not yet have the experience to understand how their actions betray their intentions.
Of course, a 'favorable moral outcome' is just that... what someone considers to be a favorable outcome. As for why a person chooses to favor a 'good' or an 'evil' outcome... that has more to do with their soul. Even good souls can be twisted into favoring evil, particularly those suffering. Evil souls can opt for good in order to cloak their greater and more sinister plans (lawful-evil vs evil-stupid). As Minamoto said, it's something of an instinct that allows us to choose one or the other, and often that instinct is a simple desire to express. Someone who is happy wants to spread that happiness and goodness. Someone who is hurt wants others to understand how they feel, and tends to spread pain (or redirect it back onto themselves).
But I am talking too much.