Multiple inheritance in Perl 6

When more than one class is mentioned in the list of base classes, we have multiple inheritance.

class A {
    method a {
        say "A.a"
    }
}

class B {
    method b {
        say "B.b";
    }
}

class C is A is B {
}

my $c = C.new;
$c.a;
$c.b;

With multiple inheritance, method resolution order is more important, as different base classes may have methods with the same name, or, for example, the two base classes have another common parent. This is why you should know the order of the base class now.

class A {
    method meth {
        say "A.meth"
    }
}

class B {
    method meth {
        say "B.meth";
    }
}

class C is A is B {
}

class D is B is A {
}

Here, the method named meth exists in both parent classes A and B, thus calling it on variables of the types C and D will be resolved differently.

my $c = C.new;
$c.meth; # A.meth

my $d = D.new;
$d.meth; # B.meth

This behaviour is confirmed by the method resolution order list, which is actually used by the compiler.

$c.^mro.say; # ((C) (A) (B) (Any) (Mu))
$d.^mro.say; # ((D) (B) (A) (Any) (Mu))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s