Virtual opBinary in interface

Ali Çehreli acehreli at yahoo.com
Fri Dec 20 19:30:15 UTC 2024


On 12/20/24 10:40 AM, Ali Çehreli wrote:
 > I always felt they could cause semantic issues.

I remembered one such case. What should happen if both Cat and Dog 
defined the "+" operator? Should we expect 'cat + dog' behave the same 
as 'dog + cat'?

Unfortunately, virtual functions are picked by the object that they are 
called on. The following example demonstrates this confusion with a 
function named mingleWith(). Different functions are called depending on 
the object.

import std.stdio;

interface Animal {
     void mingleWith(Animal);
}

class Dog : Animal {
     void mingleWith(Animal) {
         writeln("Dog with an Animal");
     }
}

class Cat : Animal {
     void mingleWith(Animal) {
         writeln("Cat with an Animal");
     }
}

void use(Animal a, Animal b) {
     a.mingleWith(b);
     b.mingleWith(a);      // <-- DIFFERENT BEHAVIOR
}

void main() {
     auto c = new Cat();
     auto d = new Dog();

     use(c, d);
}

This is too much complication for engineering, program correctness, and 
life. :)

Ali



More information about the Digitalmars-d-learn mailing list