C ++ inherits virtual functions

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 that

 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 will notice that when I initialize A as B or C, it will not run functions from B or C. I was wondering if there was anything like that? I understand that since object A, it uses the taco function, but I'm just wondering if there is any trick for getting other functions. My project is quite complicated, and I cannot know all the classes that will override A (due to the fact that plugins override the class). In addition, I must have a basic virtual function so that the body adds default behavior. Thanks.

+4
source share
1 answer

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.)

+15
source

All Articles