Access Specifiers

Access Specifiers control the accessibility of class members outside the class. They are used usually with data members and member functions. They are also used in inheritance to access the members of parent class in child class.

There are three types of access specifiers:

  • public
  • private
  • protected

Syntax:

#include <iostream>
using namespace std;

class Student {
	private: 
	//Members declared here are private
	public:
	//Members declared here are public
	protected:
	//Members declared here are protected
	
};

int main() {
    Student std;
}

Public:

When we declare our members public, we can access them anywhere outside of the class after their declaration.

specifiers.cpp
#include <iostream>
using namespace std;

class Student {
	
	public:
	//Members declared here are public
	int age = 22;
	
};

int main() {
    Student std;

    //accessing public data member
    cout << std.age;
}


Private:

When we declare our members private, we can access them only inside of the class. When we try to access the private data members outside the class, we will get error. But when we access the private data members inside the class, we can do that.

specifiers.cpp
#include <iostream>
using namespace std;

class Student {
	
	private:
	//Members declared here are private
	int age = 22;

  //accessing private data member in same class
  int myAge = age;
	
};

int main() {
    Student std;

    // We can not access private data member.
    // The following line will give error.
    // cout << std.age;
}

public members can be modified directly or indirectly from outside the class.
private members can not be changed directly from outside the class. We have to get their address in main function with the help of some public function and then at that address, we can change the value.


specifiers.cpp
#include <iostream>
using namespace std;

class Student {
	private:
		//we can not access private members
    	int marks, rollNo;
	public:
		Student(int marks, int rollNo){
			this->marks = marks;
			this->rollNo = rollNo;
		}
		//only way to get private members
		void getData(){
			cout<<"Marks = "<<marks<<endl;
			cout<<"Roll no = "<<rollNo<<endl;
		}
	
};

int main() {
    Student std(100, 1234);
    //we can not access marks directly
    std.getData();
    return 0;
}

Note: By default members of class are private. If class has data members they will be private if do not specify access specifier.


specifiers.cpp
#include <iostream>
using namespace std;

class Student {
	int marks;  
	public:
		void getData(){
			cout<<marks<<endl;
		}
};

int main() {
    Student std;
}

Protected Access Specifier:

Protected data members are accessed within the same class or in the child class. But when we try to access them outside the same class or child class, we will get an error. We will discuss this in inheritance.