Access specifiers define the visibility and accessibility of class members from outside the class boundary, serving as the primary mechanism for Encapsulation.
public: Accessible from anywhere in the program.protected: Accessible only inside the class and its derived (child) subclasses.private: Accessible strictly within the class itself (and designated friends).#include <iostream>
class Box {
private:
double width;
public:
Box(double w) : width(w) {}
// Declare a friend function granting access to private width
friend void printWidth(const Box& b);
};
// Standalone function with access to private members of Box
void printWidth(const Box& b) {
std::cout << "Box private width is: " << b.width << "\n";
}
int main() {
Box box(25.4);
printWidth(box); // Allowed!
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
How access specifiers change in derived classes.
Setting up private fields and public methods.
Using friend functions to overload stream << and >>.