Department of Engineering

IT Services

C++ - a public/private issue

When inventing a new type of object, its components can be public or private. Here's a simple example to illustrate the difference.

class publicprivate
{
private: 
  int pri;
public : 
  int pub;
};

int main() {
  publicprivate a;

  a.pub=1;
  //a.pri=1; Illegal
}

public components (like pub in this example) can be directly accessed from outside the object concerned, but private components can't. This is a useful mechanism when trying to implement "data hiding" (protecting data from being accessed maliciously, or by accident).

private components can be accessed from within the object. In the next example, a public member function is called to change the value of a private member.

class publicprivate
{
private: 
  int pri;
public : 
  int pub;
  void fun(int num) {pri=num;};
};

int main() {
  publicprivate a;

  a.pub=1;
  a.fun(1);
}

Now consider the next example.

class publicprivate
{
private: 
  int pri;
public : 
  int pub;
  void fun(publicprivate& pp) {pp.pri=999;};
};

int main() {
  publicprivate a,b;

  a.pub=1;
  //b.pri=1; Illegal
  a.fun(a);
  a.fun(b); // Legal!
}

Here, the member function takes a reference to an object and sets the private member of that object. Note that not only can a's private member be set from inside a, but b's private member can be set from inside a too.

The lesson to learn here is that privacy is not done on a per-object level, but at a per-class level - all objects of a class can access the private members of all objects of the same class.