By now, you are quite familiar with the public keyword that appears in all of our class examples of Access specifiers in c++:
Syntax of Access specifiers in c++
class MyClass { // The class public: // Access specifier class member function() { . // 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.
Also read this :- A member function of class in c++
NOTE : By default, all members of a class are private if you don’t specify an access specifier:
In C++, there are three access specifier in c++ :
- 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. You will learn more about Inheritance later.
In the following example, we demonstrate the differences between public and private members and we name it “MyClass”:
Example
class MyClass { public: // Public access specifier int x; // Public attribute private: // Private access specifier int y; // Private attribute }; void main() { MyClass myObj; myObj.x = 25; // Allowed (public) myObj.y = 50; // Not allowed (private) getch(); }
Really good website solve my question in simple