Home > Articles

  • Print
  • + Share This
Like this article? We recommend

Public Access to Data

Pay attention to issues of data hiding and encapsulation. What should be public in the class, and what should be private? A good rule of thumb is this: By default, make entities private and expose your interface explicitly by choosing what to make public.

Some of the data stored in a class should be private and not directly accessible from the outside world. Every data item that you regard as an externally accessible attribute should have an accessor function (a "reader" or "getter"). If you want the attribute to be externally changeable, changing the object's state, it should also have a mutator function (a "writer" or "setter"). My own convention is to start such a name with an underscore, and give the accessor/mutator functions the same name without the underscore:

    class MyClass
    {
     int _value;
     public: 
     MyClass(int v) : _value(v) {} 
     int value(void) const  // Accessor
     {
      return _value;
     }

     int value(int v)     // Mutator
     {
      return (_value = v)
     }
    }

    MyClass obj(123);
    obj.value(234)       // Change the attribute 
    x = obj.value       // Retrieve the value

If you use an accessor, make sure to initialize that attribute when the object is created (as shown here). Whether that value is passed as a parameter to the constructor is immaterial, but we don't want to allow a call to an accessor on an attribute that has not been initialized.

Another common convention is to use get and set prefixes for these functions. Here is the corresponding example:

     int getValue(void) const  // Accessor
     {
      return _value;
     }

     int setValue(int v)    // Mutator
     {
      return (_value = v)
     }

Also note that a mutator should return the same value it gives to the attribute because the "set" operation is analogous to an assignment. C++, like C, is expression-oriented to some extent, and we expect an assignment to return the value that was assigned, so that we can use that value if we wish:

    myvar = obj.setValue(456)

Where inheritance comes into play, protected entities are also an issue. Some things should be shared between parent and child, but not the outside world; some things are not even shared with the children at all. If you use the friend modifier on classes or methods, use it sparingly. Overuse often indicates a need to refactor the code.

  • + Share This
  • 🔖 Save To Your Account