Private type in public class scope

This tip submitted by Igor on 2012-08-02 08:24:21. It has been viewed 1401 times.
Rating of 0.0 with 0 votes

Be aware that in C++, public member variables (as well as return values and arguments of public member functions) of private nested class types are allowed (as in Java, but not C#) and can be used (not in Java or C#).
If you have no idea what I am talking about, see the following example code ;)
class C {
  // Private nested class
  struct D {
    int i;
  D d; // Valid! Private type can be exposed
  D f(D a) { return a; } // Also valid

int main()
  C c;
  //C::D d = c.d; // Error: Variable of private type (as well as a reference or a pointer to it) cannot be declared
  int i = c.d.i; // Valid! Variable of private type can be used
  c.f(c.d); // Also valid

- If you encounter the code above, don't be surprised that C::D is forbidden, while c.d is allowed
- If you write the code yourself, avoid exposing a member variable* when its type is private. Using Get and Set does not help (when the type of the variable is private); the most programmer-friendly solution is to make its type public
* Always remember that public member variables are evil

More tips

Help your fellow programmers! Add a tip!