I understand that the following code doesn't work -- can't convert base to foo.
Is there something I can do, or some pattern to employ which would get me close the behavior I'm trying to achieve in the code below? IOW, if I have a base class pointer to a derived type, how can I invoke a specific method that matches the derived type (not the base type)?
What patterns might I use? I looked into Curiously Recursive (or recurring) Template Pattern, however this imposed other limitations itself.
class base {};
class foo : public base {};
void method(const foo& f){}
int main(){
base* b = new foo();
method(*b);
}
The easiest way is probably to just make
method()
avirtual
member function onfoo
:But if for some reason that is not possible (perhaps you don't have access to
method()
or perhaps you want to keep the logic inmethod()
separate fromfoo
) you could use a simplified version of the Visitor Pattern.The visitor pattern relies on all the classes in your hierarchy having a virtual function to dispatch based on class type.
In your case you don't need double-dispatch so you don't actually need the visitor object and can just call your
method
function directly from a virtualdispatch
function:You have to remember that in most contexts the compiler doesn't know that your
base
pointer is actually of typefoo
.