Calling an overloaded method with a derived class

There is something that I am unable to do with the derived class. Basically, I have one base class with an interaction method that takes another base class object as an argument. Then I have a derived class and I want it to overload the interaction method created by the class objects should interact in its own style. So far so good, using a virtual method I get the behavior I want. However, I would also like to overload the interop method so that it can take a derived class object as an argument.

Now I have an object with a baseclass parameter. When I create such an object with a derived class as a parameter, and I make it interact with another object also created with a derived class as paramater, it calls the derived class's interaction method (as expected), but consider a method using the base class parameter. Is there a way to make it use a different method?

The code is below, I hope it will be clearer with it

#include <iostream>

class BaseClass{
public:
    BaseClass();
    virtual ~Baseclass();

    virtual void interact(BaseClass* interaction_target){std::cout << "base class interaction" << std::endl;}
};

class DerivedClass : BaseClass{
public:
    DerivedClass();
    virtual ~DerivedClass();

    virtual void interact(BaseClass* interaction_target){std::cout << "derived class interaction" << std::endl;}
    virtual void interact(DerivedClass* interaction_target){std::cout << "interaction eased by the fact that two DerivedClass object are interacting" << std::endl;}
};

class MyObject{
protected:
    BaseClass* interactor;
public:
    MyObject(BaseClass* param) : interactor(param){}
    virtual ~MyObject();

    void ObjectInteraction(MyObject interaction_target){interactor->interact(interaction_target.interactor);}
};

int main(){

MyObject first_obj(new DerivedClass());
MyObject sec_obj(new DerivedClass());

first_obj.ObjectInteraction(sec_obj); // prints derived class interactions, whereas I would like
// it to use the second method ie. interact(DerivedClass*)
return 0;
}

      

Can this be done at all?

+3


source to share


1 answer


Yes. What you are trying to do here is called "double send" or more broadly, " multiple send ". C ++ doesn't support it directly (some languages ​​do), but you can implement it yourself using the visitor pattern .



+3


source







All Articles