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
Since overloading is resolved at compile time, you need to supply the compiler with enough information to decide on the proper overload of bar
to call. Since you wish to make that decision dynamically based on the run-time type of the object, virtual functions would be of great help:
struct A {
virtual void bar() { bar(*this); }
};
struct B : public A {
virtual void bar() { bar(*this); }
};
It may seem like the bodies are identical, so B::bar
could be eliminated, but this is not true: although the bodies look exactly the same, they call different bar
s due to the static resolution of overloads in C++:
A::bar
the type of *this
is A&
, so the first overload is called.B::bar
the type of *this
is B&
, so the second overload is called.Modify the calling code to call the member bar
will complete the change:
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();