0

Hi, I have the following class and main method:

class Employee
{
      vector<string> v;
      string name;
      int i;
      public:
      Employee(){}
      Employee(string &n): name(n), i(0){}
      
      
      void read(vector<string *> &vec)
      {
           string n;
           for(int i = 0; i !=3; i++)
           {
                   cin>>n;
                       Employee e(n);
                       vec.push_back(&n);
           }
      }     
}; 

int main()
{
    vector<string *> v;
    Employee e;
    e.read(v);
    
    for(int i = 0; i !=v.size();++i)
    {
            cout<<"In the main method loop"<<endl;
            cout<<*v[i]<<endl;
            
    }
    cout<<v.size()<<endl;
    system("pause");
    return 0;
}

Now upon trying to access the vector after I am back in the main method, the program crashes. Does anyone know why?

Many thanks

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Grub
0

delete line 17 because it is a do-nothing line.

line 18 is pushing a pointer to an object that disappears from scope as soon as the function returns to main() -- the pointers are immediately invalidated. Why use a vector of pointers anyway? Just do this: vector<string> vect; and everything will work as you expect.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.