Dremendo Tag Line

Access Specifiers in C++ Programming

OOPs in C++

In this lesson, we will understand what is Access Specifiers in C++ and how to implement them in class object programming.

What is Access Specifiers in C++?

In C++, access specifiers are used to specify the access level of a class or its members (data and methods). There are three access specifiers in C++:

  • public: When we declare class members as public, they are accessible from outside the class.
  • private: When we declare class members as private, they are only accessible within the class and are not accessible from outside the class.
  • protected: When we declare class members as protected, they are only accessible within the class and its derived classes but not accessible from outside the class.

We already know from the previous lessons how to use private and public access specifiers in a C++ program. Now, we will see how to use a protected access specifier in a C++ program.

video-poster

Example

#include <iostream>

using namespace std;

class student
{
  protected:
    int eng;
    int math;
};

class result : public student
{
  private:
    int total;
    float per;

  public:
    void input()
    {
        cout<<"Enter English: ";
        cin>>eng;
        cout<<"Enter Math: ";
        cin>>math;
    }

    // Creating an instance method to calculate and store total and percentage
    void calculate()
    {
        total=eng+math;
        per=(total/200.0)*100;
    }

    void show()
    {
        cout<<"English: "<<eng<<endl;
        cout<<"Math: "<<math<<endl;
        cout<<"Total Marks: "<<total<<endl;
        cout<<"Percentage: "<<per<<endl;
    }
};


int main()
{
    result x;
    x.input();
    x.calculate();
    x.show();

    return 0;
}

Output

Enter English: 74
Enter Math: 88
English: 74
Math: 88
Total Marks: 162
Percentage: 81   

In the above example, we can see that the protected data members of the student class are accessible from the result class after inheriting the student class in it.

If we try to access the protected data members of the student class from outside, it will give a compilation error. See the example given below.

Example

#include <iostream>

using namespace std;

class student
{
  protected:
    int eng;
    int math;
};


int main()
{
    student x;
    x.eng=10;

    return 0;
}

Running the above program will give compilation error.

error: 'int student::eng' is protected