Access Specifier

Access Specifier

Access Specifier

In C++, Access Specifier are used to control the visibility and accessibility of class members (data members and member functions) from outside the class. There are three access specifiers in C++:

  1. Public – Members declared as public are accessible from anywhere in the program. They can be accessed by objects of the class as well as by functions outside the class.
  2. Private – Members declared as private are only accessible from within the class. They cannot be accessed by objects of the class or by functions outside the class.
  3. Protected – Members declared as protected are accessible from within the class and its subclasses (derived classes). They cannot be accessed by objects of the class or by functions outside the class or its subclasses.

Here is an example of a class with public, private, and protected members:

				
					class MyClass {
public:
    int publicMember;       // Public member
    void publicMethod();    // Public member function

private:
    int privateMember;      // Private member
    void privateMethod();   // Private member function

protected:
    int protectedMember;    // Protected member
    void protectedMethod(); // Protected member function
};

				
			

In this example, publicMember and publicMethod() are declared as public and can be accessed from anywhere in the program. privateMember and privateMethod() are declared as private and can only be accessed from within the class. protectedMember and protectedMethod() are declared as protected and can be accessed from within the class and its subclasses.

The default access specifier for class members is private. This means that if no access specifier is specified for a member, it will be treated as private.

Join To Get Our Newsletter
Spread the love