I'd prefer the latter, myself. The idea is that storing myInt as a data member is an implementation detail. If, at some point, you decide to change that - say, you were going to calculate it from some other data, or obtain it from another class - then you would only need to change your myInt() method. Everything else is calling myInt() to get the value, and doesn't need to know where that value comes from.
If you did it the former way, you'd also have to change myFunc(), along with any other method in MyClass that also uses that value.
Honestly I would use the first because it just makes more sense intuitively to me. Why should I call a function if I have direct access? myInt() is good in a case where you need to be sure that a user of the class isn't editing the value m_myint, but in this case YOU'RE the author of the class and know all of its internals.
Although I've never coded in an environment with enforced guidelines (really just personal projects) so take that with a grain of salt.
Now what if I want to access the vector from outside? I wouldn't want to return the reference to my internal variable without declaring it const. I would like to have this, kind of, but is it possible to overload by const?
1 2 3 4 5 6 7 8 9
class MyClass
{
private:
std::vector<int> m_intVec;
std::vector<int> & intVec() {returnthis->m_intVec;}; //Same...
public:
void addInt(int n) {this->intVec().push_back(n);};
std::vector<int> const & intVec() const {returnthis->intVec();}; //... function name
}
This won't work with 2 functions taking the same arguments (intVec()) differing only by const qualifier. How would you solve this? I'd rather not have one const_intVec() and one intVec() member, but do I have a choice?
or obtain it from another class - then you would only need to change your myInt() method
yes, at the first sight it looks intriguing. But then: Are you prepared for the new behavior? Like you call that function too often or something. I'd say better use your internal variables directly
Bobruisk wrote:
This won't work with 2 functions taking the same arguments (intVec()) differing only by const qualifier
No: due to this intVec() const the second function is different. You just cannot call a non const function from a const function. Again it's better to use the internal variable directly.
The const one will be called from constant objects.
@OP: you are too eager to show your organs.
I don't see any advantage in doing void addInt(int n) {this->intVec().push_back(n);};
Suppose that you change the container.
It may be fine if you are doing something like `string::c_str()'
¿what would be the meaning of `intVec()' if you are storing in a list?
Or you realize that a queue will be better, `push_back()' does not exist so `addInt()' is broken.
If you want to allow access to the elements, provide iterators.