class awesomeClass { std::list<A> myList; //... void fillList(); }; awesomeClass
ID: 655011 • Letter: C
Question
class awesomeClass {
std::list<A> myList;
//...
void fillList();
};
awesomeClass::awesomeClass() {
fillList();
}
void awesomeClass::fillList(){
//...
foreach(A a, otherList)
myList.push_back(a); //add to list
}
Compared to :
awesomeClass::awesomeClass() {
myList = fillList();
}
std::list<A>& awesomeClass::fillList() {
//...
std::list<A> ret;
foreach(A a, otherList)
ret.push_back(a); //add to list
return ret;
}
This is just a class with an std::list as a member variable and a function which fills this list. The first fills it inside the function and the second one returns a list and assigns it to the member list.
Which of these is better style? The one which fills the list inside the function or the one which returns a list? Or is there an even better solution?
Explanation / Answer
In object orientied programming, classes have
So your first approach is correct where you call a method that sets the instance variable.
You should return a value only when that is not represented by any instance variable or it is a public method called by consumer, which doesn't have access to the instance variable.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.