Take the following program:
#include <iostream>
#include <list>
struct A
{
virtual void hello()
{ std::cout << "Hello from A\n"; }
};
struct B : public A
{
virtual void hello()
{ std::cout << "Hello from B\n"; }
};
int main()
{
std::list<A> l1;
std::list<A*> l2;
A a;
B b;
l1.push_back(a);
l1.push_back(b);
l2.push_back(&a);
l2.push_back(&b);
l1.front().hello();
l1.back().hello();
l2.front()->hello();
l2.back()->hello();
}
We declare two lists, one using instances of class A
, and one using pointers to A
. You can put instances of B
in the first list, since B
is an A
(due to inheritance). However, when you try to access the data and methods from items in the first list, you can not access data from B
the items thinks they are of class A
even if they are not.
For the second list it works though, because of the use of pointers and virtual overloading of the method.
I hope this helps a little with your question.