public,private,protected in C++

When talking about public,private, and protected in C++, two words must pop up in your head:accessibility and visibility. Unfortunately, the two academic words are just created to confuse learners as they are never defined clearly somewhere. Actually, the public, private, and protected are used to control if you can refer to (use) the member of a class somewhere. How to refer to(use) the member of a class? There are 3 methods that can be used anywhere:

  1. create an object of the class, use the object+”.”+name of the member to refer to the member
  2. create an pointer to an object of the class, use the pointer+”->”+name of the member to use the member
  3. if the member is a static member, use classname::membername to use the member

There are other methods to refer to (use) the member of a class if you are in a function of the class itself:

4. use this->membername

5. use classname::membername even the member is not static

6. directly use membername

If you’re in a function of a derived class of the class, you have also the following possibilities of using the member:

  • use this->membername
  • use classname::membername even the member is not static
  • directly use membername

Note that we just talked about the possibilities of using class member. Whether a usage is legal(compiler does not report error) or illegal(compiler reports error) is determined by where the reference(use) occurs and the public,private, or protected keywords that is applied on the member.

For public members, the 1-3 usages are legal in all places(outside the class, in the class, in a derived class of the class), 4,5,6 are legal in the class itself or its derived classes, 4,5,6 are illegal outside the class and its derived classes. For private members, all the 1-6 usages are legal in the class(‘s functions) itself, but all the 1-6 usages are illegal outside the class including the derived class. For protected members, all the 1-6 usages are legal in the class itself. All the 1-6 usages are illegal outside the class and its derived classes. In its derived classes(‘functions), only 4,5,6 are legal. Now we can know that the following usage is illegal:

class A
{
protected:
  int aa;
public:
  void fun(){}
};

class AA:public A
{
public:
  void fun1()
  {
     A a;
    a.aa=123;//illegal!!
    aa=123;//legal
    this->aa=123;//legal
    A::aa=123;//legal
    AA aa;
    aa.aa=123;//legal
  }
}

In other words, inside a class, we have all the 6 options to refer to the class’ members, whether they are public, private, or protected. But outside the class, we have fewer options to use to refer to a member of the class, even none.

 

 

Comments are closed, but trackbacks and pingbacks are open.