Home > Back-end >  Vectors in functions
Vectors in functions

Time:05-16

I have these code lines in my .cpp file:

    void Student::operator =(const Subject &a){
        vector<Subject> v;
        v.push_back(a);
    }

and I have this operator overloaded:

    ostream &operator<<(ostream &output, Student &a){
        vector<Subject>v;
        /*for (auto& a:v){
            output<<a<<endl;
        }
        */
        cout<<v.size()<<endl;
        return output;
    }

As It seems ,when Im trying to print the elements of the vector it shows that its empty. The v.size() of it is 0.

Although I have commented out another way of showing the elements,it doesnt work as well. I dont know why my vector loses its size when its used in functions. Any possible help?

CodePudding user response:

Your vector vector<Subject> v; is in each operator implementation function, and therefore is generated just locally in each function, and will be destroyed by its end. Think about declaring this vector one time, as a private member of your Student class.

  • Related