FREE E LEARNING PLATFORM
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

C++ Access Specifiers


Access specifiers define how the members (attributes and methods) of a class can be accessed.

In C++, there are three access specifiers:

1. public - members are accessible from outside the class

2. private - members cannot be accessed (or viewed) from outside the class

3. protected - members cannot be accessed from outside the class, however, they can be accessed in inherited classes.

The public keyword is an access specifier.

In the following example, we demonstrate the differences between public and private members:

Example

    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.

Note: By default, all members of a class are private if you don't specify an access specifier:

Example

class  MyClass {
  int x;   // Private attribute
  int y;   // Private attribute
};

noidatut course







Leave Comment