I asked a question earlier but it turns out my problem was not properly modeled by my example. So here is my actual problem:
- I have class
A
, and classB
inheriting fromA
, - I have two functions
foo(A&)
andfoo(B&)
, - I have a list of
A*
pointers, containing instances ofA
andB
. - How do I get to call
foo(A&)
for instances ofA
andfoo(B&)
for instances ofB
? Constraints: I can modifyA
andB
implementation, but notfoo
's implementation.
See below an example:
#include <iostream>
#include <list>
class A {
public:
};
class B : public A {
public:
};
void bar(A &a) { std::cout << "This is an A" << std::endl; }
void bar(B &b) { std::cout << "This is a B" << std::endl; }
int main(int argc, char **argv) {
std::list<A *> l;
l.push_back(new B());
l.push_back(new B());
for (std::list<A *>::iterator it = l.begin(); it != l.end(); ++it)
bar(**it);
}
Although I am using a container with pointers, bar
is called with object from the parent class, not the child class:
# ./a.out
This is an A
This is an A
#
I was expecting
This is a B
Passing pointers to bar
(by rewriting its signature) does not help.
Thx to Antonio for helping clarifying the question.