C++ Access Modifiers



C++ is a popular programming language that is widely used in developing various software applications. In C++, access modifiers play a crucial role in controlling the visibility and accessibility of class members. 

In this article, we will discuss access modifiers in C++ and how they are used to control the access to class members.


Access modifiers are keywords used to specify the access levels of class members. In C++, there are three types of access modifiers: public, private, and protected.

 These access modifiers determine the visibility of class members within the class and outside of it.


Public access modifier The public access modifier allows class members to be accessible from anywhere in the program. 

When a class member is declared as public, it can be accessed by any code that has access to the class. 

For example, consider the following class declaration:


java code


class Car

 {

 public:

 int speed; 

void accelerate(int increase); 

}; 


In this class, the speed data member and the accelerate member function are declared as public. 

This means that any code that has access to the Car class can modify the speed data member and call the accelerate member function.


Private access modifier The private access modifier restricts the access to class members to only the members of the same class.

 When a class member is declared as private, it cannot be accessed by code outside of the class.

 For example, consider the following class declaration:


csharp code


class BankAccount 

private: 

int balance; 

void deductFees();

 }; 


In this class, the balance data member and the deductFees member function are declared as private.

 This means that only the members of the BankAccount class can modify the balance data member and call the deductFees member function.


Protected access modifier The protected access modifier is similar to the private access modifier in that it restricts the access to class members to only the members of the same class. 

However, protected members can also be accessed by the members of derived classes. For example, consider the following class declaration:


csharp code


class Animal 

{

 protected: 

int age;

 void grow();

 }; 


In this class, the age data member and the grow member function are declared as protected. 

This means that the members of the Animal class and its derived classes can modify the age data member and call the grow member function.


In summary, access modifiers are used to control the visibility and accessibility of class members in C++. 

Public members can be accessed from anywhere in the program, private members can only be accessed by members of the same class, and protected members can be accessed by members of the same class and its derived classes.

 Understanding access modifiers is essential in creating well-designed and secure classes in C++.