Access Specifiers in C++ Example

Access Specifiers in C++ Example

In C++, access specifiers control the visibility and accessibility of class members (variables and functions) from outside the class.

Type of access specifiers in C++

  • Public
  • Private
  • Protected

Public

  • Members declared as public are accessible from anywhere, both within and outside the class.
  • Public members can be accessed using object instances of the class, regardless of whether the code is inside or outside the class definition.
  • Public members are often used for the interface of the class, providing a way for external code to interact with the class. for example
1class MyClass {
2public:
3    int publicVar;
4
5    void publicFunction() {
6        // Code here
7    }
8};

Private

  • Private members can only be accessed from within the class where they are declared.
  • Private members cannot be accessed directly by external code or derived classes.
  • Private members are typically used for internal implementation details of the class, encapsulating data and behaviors that should not be exposed.
Example:
1class MyClass {
2private:
3    int privateVar;
4
5    void privateFunction() {
6        // Code here
7    }
8};

Protected

  • Members declared as protected are similar to private members but have one key difference: they can be accessed by derived classes.
  • Protected members are used when you want to allow derived classes to access certain internals of the base class while still preventing external code from accessing them directly.
Example:
1class MyBaseClass {
2protected:
3    int protectedVar;
4
5    void protectedFunction() {
6        // Code here
7    }
8};
9
10class MyDerivedClass : public MyBaseClass {
11public:
12    void accessProtectedMember() {
13        protectedVar = 42;  // Accessing protectedVar from the derived class
14        protectedFunction(); // Accessing protectedFunction from the derived class
15    }
16};

Conclusion

Access specifiers in C++ are used to control the visibility and accessibility of class members. Public members are accessible from anywhere, private members are only accessible from within the class, and protected members are accessible from derived classes but not from external code.