Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ cast vector<Inherited*> to vector<abstract*>

class Interface{};

class Foo: public Interface{};

class Bar{
public:
    vector<Interface*> getStuff();
private:
    vector<Foo*> stuff;
};

How do I implement the function getStuff()?

like image 707
Mat Avatar asked Oct 08 '10 14:10

Mat


People also ask

Can you inherit STD vector?

This means you cannot access to your class via std::vector pointer. The STL library doesn't be designed to be inherited, I guess. I would recommend III).

Can you make a vector of an abstract class?

You can't instantiate abstract classes, thus a vector of abstract classes can't work. You can however use a vector of pointers to abstract classes: std::vector<IFunnyInterface*> ifVec; Show activity on this post.

Can you inherit an STD?

Some STIs, such as syphilis, cross the placenta and infect the baby in the womb. Other STIs, like gonorrhea, chlamydia, hepatitis B, and genital herpes, can pass from the mother to the baby as the baby passes through the birth canal.


1 Answers

I am using this. It is not very nice, but fast I think :)

vector<Interface*> getStuff()
{
    return *(std::vector<Interface*> *)&stuff;
}

And you can also return only reference to the vector with this method

vector<Interface*> &getStuff()
{
    return *(std::vector<Interface*> *)&stuff;
}
like image 94
Loqenc Avatar answered Oct 08 '22 06:10

Loqenc