themmfa
themmfa

Reputation: 539

How to push_back to a list with getter function?

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;
}

Upvotes: 1

Views: 192

Answers (2)

walid barakat
walid barakat

Reputation: 475

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?.

Upvotes: 1

acraig5075
acraig5075

Reputation: 10756

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.

Upvotes: 1

Related Questions