Access Specifiers
Access specifiers in C++ are keywords used to define the accessibility of class members (data members and member functions) from outside the class. There are three access specifiers in C++:
- Public: Members declared as public are accessible from outside the class. They can be accessed by objects of the class and by functions outside the class. Public members form the interface to the class.
- Private: Members declared as private are accessible only within the class. They cannot be accessed directly by objects of the class or by functions outside the class. Private members are used to hide the internal implementation details of the class.
- Protected: Members declared as protected are similar to private members but with an additional accessibility in derived classes. Protected members are accessible within the class and by derived classes. They are useful for implementing inheritance and defining base class functionalities that derived classes can access.
Here’s how access specifiers are used in a class definition:
class MyClass {
public:
// Public members
int publicVar;
void publicMethod();
private:
// Private members
int privateVar;
void privateMethod();
protected:
// Protected members
int protectedVar;
void protectedMethod();
};
In this example:
publicVar
,publicMethod()
,privateVar
,privateMethod()
,protectedVar
, andprotectedMethod()
are members of the classMyClass
.publicVar
andpublicMethod()
are accessible from anywhere.privateVar
andprivateMethod()
are accessible only within the classMyClass
.protectedVar
andprotectedMethod()
are accessible within the classMyClass
and its derived classes.
Access specifiers help in enforcing encapsulation and defining the visibility of class members, which is essential for designing modular, maintainable, and secure code in C++.
We demonstrate the differences between public
and private
members:
#include <iostream>
using namespace std;
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myVar;
myVar.x = 25; // Allowed (x is public)
myVar.y = 50; // Not allowed (y is private)
return 0;
}
Output:
prog.cpp: In function ‘int main()’:
prog.cpp:14:9: error: ‘int MyClass::y’ is private within this context
14 | myVar.y = 50; // Not allowed (y is private)
| ^
prog.cpp:8:9: note: declared private here
8 | int y; // Private attribute
| ^
If you try to access a private member, an error occurs.