You must store pointers in deque , since polymorphism only works with reference and pointer types. When you paste these objects into deque , copies are created from type A , "cut" the parts that made them B or C initially.
Similarly, A r = B() creates a temporary B and copies its part A to A , called r .
By the way, through A a = A(); you could write A a; . They are not exactly equivalent, but they do the same job here, and you probably intended for a simpler version.
A a; B b; C c; a.taco(); //Class A b.taco(); //Class B c.taco(); //Class C // With pointers and containers deque<A*> aa; aa.push_back(&a); aa.push_back(&b); aa.push_back(&c); for (int i=0; i<aa.size(); i++) aa[i]->taco(); // Hurray! // With refs B q; A& r = q; r.taco(); // Class B!
(Just remember that those objects A , B and C have automatic storage durations. When they go out of scope, if deque still exists, all its elements are invalid pointers. Want to use dynamic allocation to further control the lifetime of the objects A , B and C .. but I will leave this as an exercise for the reader.)
source share