16

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

N. F.
  • 891
  • 3
  • 9
  • 33
  • 1
    Accessor (or getter) methods allow you to access members of a data structure, while Mutator (or setter) methods allow you to change values of a data structure. – Chad Mar 09 '12 at 00:18

2 Answers2

25

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

Here's an example:

class MyBar;

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

    private:
        MyBar mMyBar;
}

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

  • You know when they are accessed (and can debug this via a breakpoint).
  • The mutator can validate the input to ensure it fits within certain constraints.
  • If you need to change the internal implementation, you can do so without breaking a lot of external code -- instead you just modify the way the accessors/mutators reference the internal data.
LeopardSkinPillBoxHat
  • 28,915
  • 15
  • 75
  • 111
4
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 probably a dozen other terms.

Duck
  • 26,924
  • 5
  • 64
  • 92
  • 4
    Your accessor should be const! :) – Wesley Petrowski Mar 09 '12 at 00:30
  • 3
    @Wesley Petrowski - fair enough but shouldn't everyone else's be too? – Duck Mar 09 '12 at 00:56
  • Yup, everyone elses should be too, but I didn't want to spam comments on every answer. +1 for you! – Wesley Petrowski Mar 09 '12 at 02:08
  • @Wesley - I made mine `const` too, just for completeness. – LeopardSkinPillBoxHat Mar 09 '12 at 03:32
  • The question is about OO terminology; the only hint that OP cares about C++ is in the tag. Making functions `const` is just part of the C++ "anti-OO" B.S. that isn't really related to the concepts of accessor and mutator. The fact that the accessor doesn't change the state is enough to make it an accessor. `const` just means we can invoke the accessor on `const` qualified object or similarly qualified references thereto. `const` allows for different overloads to coexist, but that's specifically when mutation is going on: the overloaded function isn't an abstract accessor. – Kaz Sep 23 '14 at 05:08