Aug 28, 2004

The Scope of Class Data Members...

Herb Sutter and Jim Hyslop's Conversations Column from the June issue of C++ Users Journal (or #48) talks about the scope of data members. While it is generally widely acceptable to not place your data members in the public scope, “Getting Abstractions” reminds us about the evils of protected data members.

According to the article, The Design and Evolution of C++ (a book I do not yet own) discusses the complete history behind protected data, and also the reason why the person who recommended it now recommends against it. Since the entire reason for not having public data members is to provide an abstraction in the event that the member is refactored (renamed or removed), this naturally extends to protected data members, especially for class hierarchies that are public, not to fail to mention how Herb also recommends that all virtual functions should be private, which also works in a similar fashion.

Many RAD tools (such as Borland's VCL) make it look like there are public data members, but in reality, these are properties, and properties still call functions. When a function is called, other operations could be done, such as the example within the article, where when Bob changed the font, he had to explicitly call the repaint method; with a function, these two operations could be hidden from the user, and likewise, changes to the internal structure of the class could likewise be hidden. As there are some camps against getters and setters, the article also mentions that getters and setters should be preferred to public data members, but not when other abstractions would be better suited. In other words, you do not want to expose your current implementation of the class; instead you want to expose characteristics of that class.

Globally, it good reminder of data scopes within a class.

Filed In