Home > Software engineering >  polymorphism with vector and function?
polymorphism with vector and function?

Time:01-04

I have basically the following code:

class A{/*something*/};

class B : public A{/*something else*/};

void foo(B* aux){/*something something*/}

int main()
{
    vector<shared_ptr<A>>content;
    content.emplace_back(new B());
    foo(content[0].get());//error, invalid conversion from A to B
    return 0;
}

Trying to compile this gives the "invalid conversion" error. Is there any way to use the foo function while keeping a vector of A?

Edit: sorry, I should have been more specific: yes, A is a virtual class. What I'm trying to do is: there are 3 classes that inherit from A (B,C and D), and it would be extremely convenient if I could store them all in a single place (there may be a lot of them, and using one vector for each is a hassle) and as they are all "A", I figured a vector of A would be the best idea, however there are some functions that need specific classes of objects in this vector- like the foo in this case. I could just make multiple vectors but I decided to check for suggestions first, thus my question.

CodePudding user response:

If you're going to use polymorphism, perhaps this:

class A {
public:
    virtual void foo();
};

class B {
public:
    void foo() override;
};

If you typecast from an A* to a B* like you've done, how do you know it's really a B*?

CodePudding user response:

B is always an A, but A is not necessarily always a B, so your foo function cannot accept an A as a B. You could use a dynamic_cast to check whether A is a B for a specific runtime instance, and then call foo after you know for sure that it is a B, but in most cases that is not the best design (see static vs dynamic polymorphism).

  •  Tags:  
  • Related