Operator overloading revisited

Discussion in 'Perl Misc' started by Sisyphus, Jun 11, 2004.

  1. Sisyphus

    Sisyphus Guest

    Hi,

    Say I have 2 modules, called module_x and module_y, and that both
    modules overload the * operator (with a subroutine named over_mul).

    let's further assume that I run the following script:

    use warnings;
    use module_x;
    use module_y;
    my $x = module_x->new(10);
    my $y = module_y->new(12);

    my $z1 = $x * $y;
    my $z2 = $y * $x;

    It looks to me that the first multiplication will use the
    module_x::eek:ver_mul subroutine, and that the second multiplication will
    use the module_y::eek:ver_mul subroutine - and that there's nothing one can
    do to change that behaviour - ie I can't write 'my $z = $x * $y;' and
    "trick" it into using the module_y::eek:ver_mul subroutine.

    Now that all seems quite sane to me, but I know from past experience
    that doesn't mean that I've necessarily got it right.

    Basically, all I'm asking is that someone let me know if I'm wrong.

    Cheers,
    Rob
     
    Sisyphus, Jun 11, 2004
    #1
    1. Advertisements

  2. Sisyphus

    Anno Siegel Guest

    Ah... Cross-class overloading. A lot of fun can be had with that.

    Basically, you're right. If the classes know nothing about each other,
    the behavior you describe is what you get. If both operands overload
    an operator, the left operand wins out. The name of the implementing
    method is not relevant here, btw.

    If the classes are allowed to know about each other, the overload
    routine can check its second operand and implement a different
    behavior.

    Anno
     
    Anno Siegel, Jun 11, 2004
    #2
    1. Advertisements

  3. Sisyphus

    Sisyphus Guest

    Yes - and that probably includes "fun" in the sense of hair removal :)
    Yep - that's mainly what I was wanting to know.
    Haven't thought much along those lines ... but it's worth some
    considerstion, at least.

    Thanks Anno.

    Cheers,
    Rob
     
    Sisyphus, Jun 13, 2004
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.