Your problem is called slicing and you should check this question: Learning C++: polymorphism and slicing
You should declare this list as a list of pointers to A
s:
list<A*> listOfAs;
and then insert these aB
and aC
pointers to it instead of creating copies of objects they are pointing to. The way you insert elements into list is wrong, you should rather use push_back
function for inserting:
B bObj;
C cObj;
A *aB = &bObj;
A *aC = &cObj;
listOfAs.push_back(aB);
listOfAs.push_back(aC);
Then your loop could look like this:
list<A*>::iterator it;
for (it = listOfAs.begin(); it != listOfAs.end(); it++)
{
(*it)->say();
}
Output:
B Sayssss....
C Says
Hope this helps.