Access specifiers

Access specifiers

There are three access specifiers in C++ language. They specify the visibility of class members. Example:

class MyClass{
public:
	// data and functions in here have public access / visibility
protected:
	// data and functions in here have protected access / visibility
private:
	// data and functions in here have private access / visibility
};

If all three are omitted the default class member visibility is private.

Public

The public: access specifier marks class members as visible both from inside the class (via class members) and outside of the class (via object of a class).

#include <<iostream>
class MyClass{
public:
	int x;
	void printX(){ // x can be accessed through a member function
		std::cout << x << std::endl;
};

int main(){
	MyClass o; 
	o.x = 123; // x can be accessed through an object
	o.printX(); // member function can also be accessed through an object
}

Protected

The protected: access specifier marks class members as visible both from inside the class (via class members) and outside of the class but only through inheritance - explained in next chapter.

#include <iostream>
class MyClass{
protected: // the protected access specifier
	int x;
	void printX(){ // x can be accessed through a member function
		std::cout << x << std::endl;
	}
};
class DerivedClass : public MyClass{
public:
	void myFunction(){ // can access both x and printX() from parent class
		x = 123;
		printX();
	}
};

int main(){
	// MyClass o;
	// o.x = 123;  error! because x is protected
	// o.printX(); error! because printX() is protected
	DerivedClass o2;
	o2.myFunction();
}

Private

The private: access specifier marks class members as visible only from inside the class (via class members).

#include <<iostream>
class MyClass{
private:
	int x;
	void printX(){ // x can be accessed through a member function
		std::cout << x << std::endl;
};

int main(){
	MyClass o; 
	o.x = 123; // error! x has private visibility
	o.printX(); // error! printX() has private visibility
}

There are exceptions to this rule but for the sake of simplicity we will assume the private class members are only accessible from within a class.