0

I'm using double dispatch to obtain the distance between 2 objects of 2 classes(B, C) that are subclasses of another (A). I think that the methods in class A should be pure virtual, but them are used in a test elsewhere, so the class A must be instantiable, so I can't make them pure virtual, right?

Another thing is that I'm not sure if I'm using double dispatch in a good way, since sometimes generates a infinite loop, in the definition of Distance(A *a) in the base class.

In the class A, I have the methods:

virtual double Distance(A *a)  {return a->Distance(this);}
virtual double DistanceB(B *b) {return std::numeric_limits<double>::max();}
virtual double DistanceB(C *c) {return std::numeric_limits<double>::max();}
virtual double DistanceC(B *b) {return std::numeric_limits<double>::max();}
virtual double DistanceC(C *c) {return std::numeric_limits<double>::max();}

In the class B:

double B::Distance(A *a)  { return a->DistanceB(this); }
double B::DistanceB(B *b) { /*calculate distance*/ }
double B::DistanceC(C *c) { return c->DistanceB(this); }

In the class C:

double C::Distance(A *a)  { return a->DistanceC(this); }
double C::DistanceB(B *b) { /*calculate distance*/ }
double C::DistanceC(C *c) { /*calculate distance*/ }
starsplusplus
  • 1,232
  • 3
  • 19
  • 32
scepeda
  • 451
  • 7
  • 14

2 Answers2

0
virtual double Distance(A *a)
{return a->Distance(this);}

So if I have:

A* a1, a2;

And I call:

a1->Distance(a2);

The aforementioned implementation will call

a2->Distance(a1);

Which will call:

a1->Distance(a2);

...And that's an infinite loop.

PaF
  • 3,297
  • 1
  • 14
  • 15
0

Since A is not pure abstract, you have to provide also :

virtual double DistanceA(A *a);
virtual double DistanceA(B *b);
virtual double DistanceA(C *c);
virtual double DistanceB(A *a);
virtual double DistanceC(A *a);

And fixing

double A::Distance(A *a) {return a->DistanceA(this); }
Jarod42
  • 203,559
  • 14
  • 181
  • 302