Access Specifiers in C++

When a class is defined the private, public and protected keywords are the access specifiers. An access specifier defines how the members of the class like data members and member functions can be accessed. Data members and functions which are under public keyword is accessible from outside the class. Data members and functions under private keyword are not accessible from outside the class. Data members and functions under protected keyword are accessible from inherited class. 

The following program shows a class with a public keyword. The data member under public ‘int age‘ is accessible from outside the class with object obj1

#include<iostream>
using namespace std;

class person {
    public:
    int age;
};

int main () {

    person obj1;
    obj1.age = 25;

    cout<<"The age of the person is "<<obj1.age;

    return 0;
   
}

Output:

The age of the person is 25

The following program shows the use of a private keyword. Data member ‘Int age‘ is not accessible from outside the class. So a member function showAge() under public keyword is created to access the private members. Data members and functions are accessed using an object of the class. 

#include<iostream>
using namespace std;

class person {
    private:
    int age;

    public:
    void showAge(int a) {
    age = a;
    cout<<"The age of the person is "<<age;

    }

};

int main () {
    int b;

    person obj1;
    b = 25;

    obj1.showAge(b);

    return 0;
}

Output:

The age of the person is 25

The following program shows the use of a protected keyword. The protected data member ‘int sal‘ is accessed using inheritance. Class person is inherited to class salary. An object of class salary is created to access the data member.

#include<iostream>
using namespace std;

class person {
    protected:
    int sal;
};

class salary : public person {
    public:
    void showSalary(int a) {
        sal = a;

        cout<<"The salary of the person is "<<sal;
    }
};

int main () {

    int b;

    salary obj1;
    b = 5000;

    obj1.showSalary(b);

    return 0;

}

Output:

The salary of the person is 5000
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments