I asked a question earlier but it turns out my problem was not properly modeled by my example. So here is my actual problem:
A
, and c
You are looking for run-time polymorphism. This is supported "naturally" for virtual member methods.
An alternative would be to use RTTI and dynamically cast A*
to B*
and call bar
upon success... or static_cast
if you are really sure there are B*
objects. Generally need to down-cast indicates problematic design.
Important note: Run-time check in dynamic_cast requires the type to be polymorphic anyways. Maybe your particular A
fulfills this but you just can't change the class. If not, static_cast
is the only option available.
If you have control over class you, can use standard polymorphism and overload mechanisms using virtual methods on this
as a facade for the "external" call:
#include
#include
class A;
void external_bar(A&);
class A {
public:
virtual void bar() { external_bar(*this); };
};
class B;
void external_bar(B&); //IMPORTANT
class B : public A {
public:
virtual void bar() { external_bar(*this); };
};
void external_bar(A &a) { std::cout << "This is an A" << std::endl; }
void external_bar(B &b) { std::cout << "This is a B" << std::endl; }
int main(int argc, char **argv) {
std::list l;
l.push_back(new B());
l.push_back(new B());
for (std::list::iterator it = l.begin(); it != l.end(); ++it)
(*it)->bar();
}
This also has drawbacks. Forward declarations are needed. And you need to take care everything is defined properly, because if you forget line // IMPORTANT
the compiler will pick up the definition of external_bar
for A&
as it is implicitly convertible, and you might get quite a headache spotting the error.