C++ Access Specifiers

Access specifiers are used in C++ to define the degree of access that members of a class have to outsiders. In C++, there are three types of access specifiers: protected, private, and public.

Public Access Specifier:

Anyone in the programme can access a public member of a class. Anyone outside of the class can access members who have been designated as public.

Syntax:

class ClassName {
   public:
      // public members go here
};

Example:

class Car {
   public:
      string model;
      int year;
};

int main() {
   Car myCar;
   myCar.model = "Ford Mustang";
   myCar.year = 2022;
   cout << "Model: " << myCar.model << endl;
   cout << "Year: " << myCar.year << endl;
   return 0;
}

Output:

Model: Ford Mustang
Year: 2022

Private Access Specifier:

A class’s private members can only be accessible by other members of the class. Private members cannot be accessed from outside the class.

Syntax:

class ClassName {
   private:
      // private members go here
};

Example:

class Employee {
   private:
      string name;
      double salary;
   public:
      void setSalary(double s) {
         salary = s;
      }
      void printSalary() {
         cout << "Salary: " << salary << endl;
      }
};

int main() {
   Employee emp1;
   emp1.setSalary(5000);
   emp1.printSalary();
   // emp1.salary = 6000; // This line will give an error as salary is a private member
   return 0;
}

Output:

Salary: 5000

Protected Access Specifier:

Inside a class and its derived classes, a protected member may be accessed. Protected members cannot be accessed from outside the class.

Syntax:

class ClassName {
   protected:
      // protected members go here
};

Example:

class Animal {
   protected:
      string name;
   public:
      void setName(string n) {
         name = n;
      }
};

class Dog: public Animal {
   public:
      void printName() {
         cout << "Name: " << name << endl;
      }
};

int main() {
   Dog myDog;
   myDog.setName("Buddy");
   myDog.printName();
   // myDog.name = "Max"; // This line will give an error as name is a protected member
   return 0;
}

Output:

Name: Buddy