Up until now, you have seen the public keyword in all of our class examples. This keyword is an access specifier.
Access specifiers determine how the members (attributes and methods) of a class can be accessed from outside the class.
In C++, there are three access specifiers:
public - Members are accessible from outside the class.private - Members cannot be accessed (or viewed) from outside the class.protected - Members cannot be accessed from outside the class, however, they can be accessed in inherited classes (we will learn about this in the Inheritance chapter).Let's look at an example demonstrating the difference between public and private.
#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 myObj;
myObj.x = 25; // Allowed (public)
// myObj.y = 50; // ERROR: Not allowed (private)
cout << "x is: " << myObj.x << "\n"; return 0; }
If you try to uncomment the line myObj.y = 50;, the compiler will throw an error because y is private. It can only be accessed by methods inside the MyClass itself.
By default, all members of a class in C++ are: