Session 9
Session 9
By now, you are quite familiar with the public keyword that appears
in all of our class examples:
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
The public keyword is an access specifier. Access specifiers
define how the members (attributes and methods) of a class can
be accessed. In the example above, the members are
public - which means that they can be accessed and modified from
outside the code.
Example
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; // Not allowed (private)
return 0;
}
If you try to access a private member, an error occurs:
error: y is private
Note: It is possible to access private members of a class
using a public method inside the same class.
See the next chapter (Encapsulation) on how to do this.