What is the difference between accessor and mutator methods?

How are different accessors and mutators? An example and explanation would be wonderful.

+7
source share
2 answers

accessor is a class method used to read data, and a mutator is a class method used to change data members.

Here is an example:

class MyBar; class Foo { public: MyBar GetMyBar() const { return mMyBar; } // accessor void SetMyBar(MyBar aMyBar) { mMyBar = aMyBar; } // mutator private: MyBar mMyBar; } 

It is best to make data members private (as in the example above) and access them only through accessors and mutators. This occurs for the following reasons:

  • You know when they are available (and can debug this through a breakpoint).
  • The mutator can validate the input to meet certain restrictions.
  • If you need to change the internal implementation, you can do this without breaking a lot of external code - instead, you just change the way accessors / mutators refer to internal data.
+14
source
 class foo { private: int a; public: int accessA() const { return(a);} void mutateA(const int A) { a = A;} } 

Also known as getters and setters, and perhaps a dozen other terms.

+3
source

All Articles