ok say we now have the next classes
class A class B: public A class C : public A
If I actually do this
A a = A() B b = B() C c = C() a.taco() //Class A b.taco() //Class B c.taco() //Class C deque<A> aa = deque<A>() aa.push_back(a) aa.push_back(b) aa.push_back(c) for(int i=0i<aa.size()i++) aa[i].taco()//All Class A A r = B() r.taco() //Class A
Now you will find after i initialize A as B or C, it will not fire the functions from B or C. I'm wondering if there is in whatever way for this? I realize the notion that because the object is really a it uses A's taco function, however i only agreed to be wondering if there is some trick for you to get in the other functions. My project is rather complicated, and that i can't understand all the classes which will override A(because of plug ins overriding a category). Also, I kinda must have the bottom virtual function possess a body to include default behavior. Thanks.
You have to store pointers within the
deque, since polymorphism is only for reference &lifier pointer types. Whenever you place individuals objects in to the
deque, copies are constructed with type
A, "slicing" from the parts that built them into
A r = B() just produces a brief
B and copies the
A some of it into an
A known as
A a = A() you may as well write
A a. They are not completely equivalent, however they perform the same job here, and also you likely intended for the more 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= i<aa.size() i++) aa[i]->taco() // Hurray! // With refs B q A&lifier r = q r.taco() // Class B!
(Keep in mind that individuals objects
c have automatic storage duration. As soon as they walk out scope, when the
deque still is available then its elements are invalid pointers. You might want to employ dynamic allocation to help control the duration of the
C objects.. but I'll leave that being an exercise towards the readers.)