As a C++ beginner, I didn't thought about that much until now, but if I want to access an attribute from inside a class itself, should I access the attribute directly or use a getter function?
class foo
{
public:
  int getVal();
  void bar();
private:
  int val;
}
foo::bar()
{
  int val = this->getVal();
  // or
  int val2 = this->val;
}
I would like to know that for
a) what is better design and (more importantly for me)
b) any performance differences (maybe because of the overhead calling the function)?
I normally use the getter method even inside the class in case I ever want to rename the attribute. But now I'm writing a method, which will access the attribute quite (very) often.
Inside the class always use the attribute itself. The reason you have a getter is to make a certain value available to other classes. Be careful with automatically making getters for every attribute you use. It is considered bad design to expose the inner workings of a class. Sometimes it makes sense to make an attribute available, sometimes it is just for internal use and other classes have no business inspecting them.
If you like to know more about this google "getters setters evil" Some of the articles you may find are quite extreme but they will explain why they feel that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With