1

I have getter setter function like this.

void Student::setStudentName(std::__cxx11::string b)
{
    cout<<"Enter the student name"<<endl;
    cin >> studentName;
    int size = b.size();
    if(size > 0 && size<20)
        studentName = b;
    else
        cout<<"Please enter a name between 1-20 char"<<endl;
}
string Student::getStudentName() const
{
    return studentName;
}

What i want to do is add to the list with getter function.

void Student::addStudent()
{
    int studentAdd;
    cout<<"How many student do you want to add?"<<endl;
    cin>>studentAdd;

    for(int i=0;i<studentAdd;++i)
    {
        setStudentName("a");
        getStudentList().push_back(getStudentName());
    }
}

I tried like this but

getStudentList().push_back(getStudentName()); 

this code didn't work. What could be the problem?

And here is the list's getter/setter

void Student::setStudentList(list<string> a)
{
    studentList = a;
}
list<string> Student::getStudentList() const
{
    return studentList;
}
themmfa
  • 499
  • 4
  • 15

2 Answers2

1

The problem lies with the return type of getStudentList. As it stands you're returning a copy of it, and then appending to the temporary copy, which then immediately gets destroyed.

What you want is to return a reference to the actual list.

list<string> &Student::getStudentList() {
    return studentList;
}

You then shouldn't make such a function const because it is (potentially) a mutator.


The matter of const is sometimes handled by having two overrides of getStudentList. One which is const both in return type and cv-qualifier, and one which isn't const in either.
// accessor override
const list<string> &Student::getStudentList() const { 
    return studentList;
}

// mutator override
list<string> &Student::getStudentList() { 
    return studentList;
}

This enables the appropriate override to be deduced in the different calling scenarios.

acraig5075
  • 10,588
  • 3
  • 31
  • 50
  • Thank you so much for your answer :) And i changed the setter function a little bit and it worked. – themmfa Dec 19 '19 at 11:31
1

as the answers above, you need to return a reference so you can update it by push_back, and this also explains why you need to remove const.

list<string> &Student::getStudentList() {
     return studentList;
}

note :: be aware of returning a reference to a local/not independent variable.

please take a look on Is the practice of returning a C++ reference variable evil?.

walid barakat
  • 455
  • 1
  • 6
  • 17