c sharp Logo

Access Specifiers


Access specifiers in C++ are used to control which parts of a class can be accessed from outside the class. There are three access specifiers in C++:

  • Public: Public members of a class can be accessed from anywhere in the program.
  • Protected: Protected members of a class can be accessed from within the class itself and from derived classes.
  • Private: Private members of a class can only be accessed from within the class itself.

The default access specifier for class members is private. This means that if you do not specify an access specifier for a class member, it will be private.

Example

The following code shows a simple class named Person with access specifiers:

class Person {

public:

  std::string name; // public member

 

protected:

  int age; // protected member

 

private:

  std::string address; // private member

};

 

The name member of the Person class is public, so it can be accessed from anywhere in the program. The age member of the Person class is protected, so it can be accessed from within the Person class itself and from derived classes. The address member of the Person class is private, so it can only be accessed from within the Person class itself.

Benefits of using access specifiers

There are several benefits to using access specifiers in C++, including:

  • Data encapsulation: Access specifiers can be used to encapsulate data and protect it from being modified by unauthorized code.
  • Inheritance: Access specifiers can be used to control which members of a base class can be accessed by derived classes.
  • Code readability: Access specifiers can be used to make code more readable by indicating which members of a class can be accessed from outside the class.

Example

The following code shows how to use access specifiers to protect the address member of the Person class:

class Person {

public:

  std::string GetAddress() {

    return address; // protected member can be accessed from within the class itself

  }

 

private:

  std::string address;

};

 

This code creates a public method named GetAddress() that can be used to get the address of a Person object. However, the address member itself is private, so it can only be modified from within the Person class itself.

Conclusion

Access specifiers are a powerful feature of C++ that can be used to write more robust, secure, and readable code. By understanding how to use access specifiers, you can write better C++ code.