Access Levels of a Class

Access levels define the scope of data members and member functions of a class.
By scope we mean that where and where not inside a program members of a class can be accessed.
There are three access levels of a class:
1. public
2. private
3. protected.

Let’s look at them in more depth.

Public class members

When class members are public (talking about both data members and member functions), they can be accessed directly by and member function or non-member function outside the class.
Let’s see an example for better understanding

class Student
    {
        public:         //all members are public now
        int rollNo;
        string name;
        int getRoll()
        {
            return rollNo;
        }
    };
    
    int main()
    {
        Student s1;         //object created of class Student
        s1.rollNo = 2;      //completely valid, as rollNo is public it can be directly accessed outside the class.
        cout << s1.getRoll();   //completely valid, same explaination as above 
    }

We saw in above example, that when members of class are public they can be accessed outside the class.
Public members of the class provide a public interface of class.

Private class members

Private class members are only accessed by member functions of that class only.
They are hidden from the outside world and are a good example of data abstraction.
For example,

class Student
    {
        //all these members are private by default
        int rollNo;
        string name = “Naman”;
        int getRoll()
        {
            return rollNo;
        }
        public:
        //this is public
        void print()
        {
            cout << getRoll() << endl;      //this is valid because private members can be accessed from within the class
            cout << name << endl;           //this is valid for the same reason
        }
    };
    
    int main()
    {
        Student s1;         //object created of class Student
        s1.rollNo = 2;      //this is invalid, because rollNo is now a private data member and cannot be accessed outside the class.
        cout << s1.getRoll();   //this is invlaid too, because getRoll() is now a private member.
        s1.print();         //calling a public member function from outside is valid 
    }

We saw how private data members cannot be accessed directly from outside the class.

Protected class members

Protected members of a class are very similar to private members.
They can be accessed by members functions declared within the class and cannot be accessed directly.
The only difference between them is that protected members can be inherited and private members cannot.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?