An Access Specifier can be defined as a keyword which decides how the members(Attributes and Methods) of a class can be accessed. There are basically three types of Access Specifiers i.e Public, Private and Protected; the default Access Specifiers for Class member and member functions are Private.
Types of Access Specifiers
1) Private : members can not be accessed outside of the Class.
#include<iostream>
using namespace std;
class class_Name{
private:
int data=12;
};
int main(){
class_Name object1;
cout<<object1.data<<endl;
}
// output: error::::: data can not be accessed outside the class_Name
the above code will show an error message, since data is a private member hence it can not be accessed outside the class.
2) Public : members can be accessed outside the class.
#include<iostream>
using namespace std;
class class_Name{
public:
int data=12;
};
int main(){
class_Name object1;
cout<<object1.data<<endl;
}
the output of the above code will be 12, as the data is public member of the class.
3) Protected : members can not be accessed outside the Class but they can be accessed in inherited Class. we will learn about Protected Access Specifier further in Inheritance.
How to access the private data members?
we introduce getter() and setter() member functions to access the private data members of the Class, as given in the below code:
#include<iostream>
using namespace std;
class School{
private:
int rollNo;
char ID;
public:
//getter()
int getRollNo(){
return rollNo;
}
char getID(){
return ID;
}
//setter()
void setRollNo(int rollNo){
this->rollNo=rollNo;
}
void setID(int ID){
this->ID=ID;
}
};
int main(){
School Student;
Student.setRollNo(15);
Student.setID('A');
cout<<Student.getRollNo()<<endl;
cout<<Student.getID()<<endl;
}
Here getRollNo( ) and getID( ) are getter( ) which is used to get the value of the private data members of the Class, setRollNo( ) and setID( ) are the setter( ) which is used to modify the value of data members; in the above code there is a keyword “this” is given, this is a pointer which stores the address of current object of the Class.