I have a particular scenario below. The code below should print \'say()\' function of B and C class and print \'B says..\' and \'C says...\' but it doesn\'t .Any ideas.. I a
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 As:
list 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::iterator it;
for (it = listOfAs.begin(); it != listOfAs.end(); it++)
{
(*it)->say();
}
Output:
B Sayssss....
C Says
Hope this helps.