Kelly Elton
Kelly Elton

Reputation: 4427

c++ inherit 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 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.

Upvotes: 4

Views: 1274

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385114

You must store pointers in the deque, since polymorphism only works with reference & pointer types. When you insert those objects into the deque, copies are made of type A, "slicing" off the parts that made them B or C originally.

Similarly, A r = B() just creates a temporary B and copies the A part of it into an A called r.

BTW by A a = A(); you might as well write A a;. They're not completely equivalent, but they do the same job here, and you likely meant for the 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 duration. The moment they go out of scope, if the deque still exists then all its elements are invalid pointers. You may want to employ dynamic allocation to further control the lifetime of the A, B and C objects.. but I'll leave that as an exercise to the reader.)

Upvotes: 15

Related Questions