ok say we have the following classes
class A
{
public:
virtual void taco()
{
cout << "Class A" << endl;
}
};
class B: public A
{
public:
virtual void taco()
{
cout << "Class B" << endl;
}
};
class C : public A
{
public:
void taco()
{
cout << "Class C" << endl;
}
};
Now if I 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=0;i<aa.size();i++)
aa[i].taco();//All Class A
A r = B();
r.taco(); //Class A
Now you’ll notice when I initialize A as B or C, it won’t fire the functions from B or C. I was wondering if there was any way around this? I understand the concept that since the object is A it uses A’s taco function, but I was just wondering if there was some trick to getting at the other functions. My project is fairly complicated, and I can’t know all the classes that will override A(due to plugins overriding a class). Also, I kinda need to have the base virtual function have a body to add default behavior. Thanks.
You must store pointers in the
deque, since polymorphism only works with reference & pointer types. When you insert those objects into thedeque, copies are made of typeA, “slicing” off the parts that made themBorCoriginally.Similarly,
A r = B()just creates a temporaryBand copies theApart of it into anAcalledr.BTW by
A a = A();you might as well writeA a;. They’re not completely equivalent, but they do the same job here, and you likely meant for the simpler version.(Just remember that those objects
a,bandchave automatic storage duration. The moment they go out of scope, if thedequestill exists then all its elements are invalid pointers. You may want to employ dynamic allocation to further control the lifetime of theA,BandCobjects.. but I’ll leave that as an exercise to the reader.)