Question

This is part 2 to a problem I previously asked: Is it possible to have polymorphic member overloading in C++?

Using the Wiki example I created this example. http://en.wikipedia.org/wiki/Double_dispatch

My problem is that the compiled code never looks up the vtable, and always uses the base instead of the inherited class. Here is my code:

#include <iostream>

class xEntity;
class xVehicle;

class xMapObject
{
  public:
    virtual void Bump(xMapObject&) { std::cout << "MapObject Bump MapObject\n"; };
    virtual void Bump(xEntity&) { std::cout << "MapObject Bump Entity\n"; };
    virtual void Bump(xVehicle&) { std::cout << "MapObject Bump Vehicle\n"; };
};

class xEntity : public xMapObject
{
  public:
    virtual void Bump(xMapObject&) { std::cout << "Entity Bump MapObject\n"; };
    virtual void Bump(xEntity&) { std::cout << "Entity Bump Entity\n"; };
    virtual void Bump(xVehicle&) { std::cout << "Entity Bump Vehicle\n"; };
};

class xVehicle : public xEntity
{
  public:
    virtual void Bump(xMapObject&) { std::cout << "Vehicle Bump MapObject\n"; };
    virtual void Bump(xEntity&) { std::cout << "Vehicle Bump Entity\n"; };
    virtual void Bump(xVehicle&) { std::cout << "Vehicle Bump Vehicle\n"; };
};

int main(int argv, char **argc)
{
    xEntity Entity;
    xVehicle Vechile;

    xMapObject &EntityRef = Entity;
    xMapObject &VehicleRef = Vechile;

    VehicleRef.Bump(EntityRef);

    return 0;
}

However, the output is always:

Vehicle Bump MapObject

Any help on this mystery is greatly appreciated.

Was it helpful?

Solution

You only did single dispatch, not double dispatch. The idea is that in xVehicle, taking an xMapObject&, you would call ref.bump(*this); which is double dispatch.

OTHER TIPS

It is using the vtable; that's why it's calling xVechicle::Bump()! The vtable isn't used on arguments, that doesn't make sense (in C++, at least).

The typical solution is to have e.g. Bump(xMapObject& obj) call obj.Bump(*this);.

Is a bad design the xEntity::Bump(xVehicle&) because you are using as parameter in a base class a derived class.

and at least that your contract change, you don't need redefine base Bump methods.

the problem is that you are creating the xMapRef vars, that convert your derived class to a base class.

if you want that appropriated method is called, just call with the derived class object

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top