Access Specifier in C++

C++ Access Specifier

Access specifier or access modifiers are the labels that specify type of access given to members of a class. These are used for data hiding. These are also called as visibility modes. There are three types of access specifiers:

1.private
2.public
3.protected

1.Private: If the data members are declared as private access then they cannot be accessed from other functions outside the class. It can only be accessed by the functions declared within the class. It is declared by the key word „private‟ .

2.public: If the data members are declared public access then they can be accessed from other functions out side the class. It is declared by the key word „public‟ .

3.protected: The access level of protected declaration lies between public and private. This access specifier is used at the time of inheritance.

Note: If no access specifier is specified then it is treated by default as private The default access specifier of structure is public where as that of a class is “private”.

Example :

#include<iostream.h>
using namespace std;
class Sample
{
private : int roll;
char name[30];
public :
void get_data()
{
cout<<”Enter roll number”;
cin>>roll;
cout<<”Enter Name”;
cin>>name;
}
void put_data()
{
cout<<”Roll number is:”<<roll<<endl;
cout<<”Name is : “<<name;
}
};
int main()
{
Sample sp;
sp.get_data();
sp.put_data();
return 0 ;
}


Leave a Comment

Your email address will not be published. Required fields are marked *