home > resources > c++ coding standard > online version

Accessor Styles

Accessor methods provide access to the attibutes of an object. Accessing an object's attributes directly, as is commonly done in C structures, is greatly discouraged in C++. It exposes implementation details of the object and degrades encapsulation.

There are two accepted ways to implement accessors, the preferable way is the following :

Attributes as objects

Example 4-3. Attributes as object accessor style

class X
{
public:
    int             age() const     { return mAge; }
    int&            rAge()          { return mAge; } 
    
    const String&   name() const    { return mName; }
    String&         rName()         { return mName; }
private:
    int              mAge;
    String           mName;
}

The main weakness of this approach is that when returning a reference to basic types (as in the rAge() method), it's impossible to perform checks on the provided value. To solve this, you can either create a wrapper class or resort to the second accessor implementation style. The preferred method is of course, in this example, to create an Age class which contains all consistancy checks as class methods or statements in its constructor.

The advantage of this approach is that it's more consistent with OOP : the object should do it. An object's assignment (=) operator can do all the checks for assignments. This centralizes the consistancy checks in one place, in the object, where it belongs.

When possible, use this approach instead of the One method name accessor style.

One method name

Example 4-4. One method name accessor style

class X
{
public:
    int    age() const     { return mAge; }
    void   age(int age)    { mAge = age; }
private:
    int mAge;
}

Using this approach, it's possible to include some checks about the value provided to the age() method. However these checks make only sense when handling basic types since objects should perform their checks internally. Failing to do so would mean that every accessor has to reimplement these consistancy rules over and over again

The hude drawback here is that objects aren't treated in their own right and that encapsulation somewhat fails. It is better to rely on the object's assignment operator.