0

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);
10
  • 3
    What doesn't work exactly? Note the pointer you put into V will be invalid as soon ` object` goes out of scope. Commented Mar 28, 2014 at 16:31
  • well this method works, probably something that you didn't show doesn't Commented Mar 28, 2014 at 16:32
  • It doesn't work because V is a member of the class Y. And since this cannot be a member function (because Y doesn't have any), and V is private, there cannot be an unqualified reference to V like this. Commented Mar 28, 2014 at 16:33
  • my actual program is more complex. I made this classes to explain the structure of my code. I inserted 2 objects in my vector using 2 methods: first, the one I presented in the question, and it doesn't work because I don't have the object in the vector, and another method which works: V.push_back(new X1(constructor arguments));. I was just curious why my first method doesn't work. Commented Mar 28, 2014 at 16:34
  • You are trying to address variable of the class Y without initializing its instance. Commented Mar 28, 2014 at 16:34

1 Answer 1

3

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>());
Sign up to request clarification or add additional context in comments.

1 Comment

Use std::make_shared<>() as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.