Reputation:
I have a base class with 2 derived classes and another one which store objects of the derived classes type:
class X
{};
class X1 : public X
{};
class X2 : public X
{};
class Y
{
std::vector<X*> V;
};
why doesn't this method of introducing elements in V work?
X1 object;
X *ptr = &object;
V.push_back(ptr);
Upvotes: 0
Views: 1699
Reputation: 1
I suppose you have put your sample code inside a function of class Y
and can access the class member variable V
.
The pointer to the locally declared object
variable is invalid when the function returned. You can fix this by allocating an object from the heap:
X *ptr = new X();
V.push_back(ptr);
Or even better instead of using raw pointers, use smart pointers if possible, e.g:
class Y {
std::vector<std::shared_ptr<X> > V;
};
V.push_back(std::make_shared<X>());
Upvotes: 3