I have two classes like this (simplified and renamed):
class Base
{
public:
virtual void operator()( ) { cout << "Base\n";}
};
class Derived : public Base
{
public:
void operator()( ) { cout << "Derived\n"; }
};
void doSomething( Base obj )
{
obj( );
}
int main( )
{
list<Base> bList;
Derived d1, d2, d3;
bList.push_back( d1 );
bList.push_back( d2 );
bList.push_back( d3 );
for( list<Base>::iterator it = bList.begin(); it != bList.end(); it++ )
{
doSomething( *it );
}
return 0;
}
When I run this, I get:
Base
Base
Base
i.e. the Base::operator() is called. Obviously this is not what I want to happen. I tried changing doSomething to
void doSomething( Base& obj )
but this only works if called directly with a Derived object and not with one from the list. And references can't be stored in a list.
Is there any way how I can make doSomething "see" that it has to call a derived class' function (without having to resort to pointers)?
Edit: Problem is pointed out, for other people who might run into this here is a link: What is object slicing?