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

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.

many thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.