I am trying a basic thing with two classes and a free functions. First I have two classes :
struct BASE{
BASE(int a = 0):a_(a){};
virtual ~BASE(){};
virtual void foo(){std::cout << "BASE " << std::endl;}
int a_;
};
struct DERIVED: public BASE{
DERIVED():BASE(){};
void foo(){std::cout << "DERIVED " << std::endl;}
};
then I fill up a std::vector (or boost::ptr_vector)
std::vector<BASE* > vec;
vec.push_back( new BASE(2));
vec.push_back( new DERIVED);
If I call my function foo, no pb the virtual stuff works well,
but if I create two free functions :
void foo(BASE* a, DERIVED* b){
std::cout << " mix base/derived " << std::endl;
}
void foo(BASE* a, BASE* b){
std::cout << " full base " << std::endl;
}
if I do
foo(vec[0], vec[1]); //failed
I will get the message
full base
Well it is logical because I have vector of BASE*, but does it exist anyway
to get the good call to my free function ? I need the inheritance so I can not really separate the 2 classes because I must fill up this container
Moreover at the end my vector will be fill up randomly, so I can not know by advance how cast properly.
The simplest (and quickest) way to get workaround is to introduce one more virtual function to unique identify derived classes (using
int,enumvalues ortypeid). So later you may call it and realize what exact derived class (or maybe base) you’ve got behind theBASE*, and dodynamic_castto that type.You gave no details about what problem you are trying to solve… just make sure that you’ve done a complete reaseach for existed solutions if you want to implement a Double Dispatch (or some kind of)…
But usually, if you need
dynamic_castit means that smth wrong with you design (OOP model of domain)…