Our Human class uses operator overloading to allow us to "add" two humans together and produce a child. Our implementation does require that the two objects be of opposite sex. Remember, we're talking about biological reproduction, not marriage.

While this example works as-is, we can take it a lot further by adding genes into the mix. We'll add the two genes that control eye color, and use overloading to combine the genes from the parent to model the biology.

Overloading is not a Moose-specific feature. It's a general OO concept that is implemented in Perl with the overload pragma. Overloading lets objects do something sane when used with Perl's built in operators, like addition (+) or when used as a string.

In this example we overload addition so we can write code like $child = $mother + $father.

We could just give four attributes (two of each gene) to the Human class, but this is a bit messy. Instead, we'll abstract the genes into a container class, Human::EyeColor. Then a Human can have a single eye_color attribute.

The eye color class has two of each type of gene. We've also created a coercion for each class that coerces a string into a new object. Note that a coercion will fail if it attempts to coerce a string like "indigo", because that is not a valid color for either type of gene.

As an aside, you can see that we can define several identical attributes at once by supplying an array reference of names as the first argument to has.

We also need a method to calculate the actual eye color that results from a set of genes. The bey2 brown gene is dominant over both blue and green. The gey green gene is dominant over blue.

When two eye color objects are added together, the _overload_add() method will be passed two Human::EyeColor objects. These are the left and right side operands for the + operator. This method returns a new Human::EyeColor object.