Hello folks,
I need to store references to instances of derived classes in C++. I considered using a vector of shared_ptrs to the base class (for it needs to hold different types of derived classes), however, it's important that the container holds the original pointers, which is not the case with vectors (or other stl containers), if I'm not mistaken. Is there a way to do this in native C++, or do I have to use special containers like Boost's ptr_vector?
EDIT: This is my test code:
class Foo
{
public:
Foo() {}
virtual ~Foo() {}
virtual void set_x(int i) = 0;
};
class Bar : public Foo
{
public:
Bar() {}
void set_x(int i)
{
this->x = i;
}
int x;
};
int main()
{
Bar bar;
// ptr
std::cout << &bar << "\n";
std::vector<Foo*> foos;
foos.push_back(&bar);
// different ptr value
std::cout << &foos[0] << "\n";
foos[0]->set_x(1);
// however, changes are made
std::cout << bar.x;
return 0;
}
Thanks in advance,
jena