C++ Access Specifiers

Introduction

Access specifiers in C++ determine the accessibility of members (attributes and methods) within a class. They are essential for implementing encapsulation, one of the core principles of Object-Oriented Programming (OOP). The three main access specifiers in C++ are public, private, and protected.

Types of Access Specifiers

Public

  • Members declared as public are accessible from outside the class.
  • Any part of the program can access and modify public members.

Example: Public Access Specifier

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Person person1;
    person1.name = "John Doe";
    person1.age = 30;

    person1.display();

    return 0;
}

Output

Name: John Doe, Age: 30

Explanation

  • The name and age attributes and the display method are declared as public.
  • They can be accessed and modified directly from outside the class.

Private

  • Members declared as private are accessible only within the class.
  • They cannot be accessed or modified directly from outside the class.
  • Private members can be accessed indirectly through public methods.

Example: Private Access Specifier

#include <iostream>
using namespace std;

class Person {
private:
    string name;
    int age;

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

    void setAge(int a) {
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    Person person1;
    person1.setName("Jane Doe");
    person1.setAge(25);

    person1.display();

    return 0;
}

Output

Name: Jane Doe, Age: 25

Explanation

  • The name and age attributes are declared as private.
  • They can be accessed and modified only through the public methods setName and setAge.

Protected

  • Members declared as protected are accessible within the class and its derived (inherited) classes.
  • They are not accessible from outside the class, except in derived classes.

Example: Protected Access Specifier

#include <iostream>
using namespace std;

class Person {
protected:
    string name;
    int age;

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

    void setAge(int a) {
        age = a;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

class Student : public Person {
public:
    int studentID;

    void setStudentID(int id) {
        studentID = id;
    }

    void displayStudent() {
        display();
        cout << "Student ID: " << studentID << endl;
    }
};

int main() {
    Student student1;
    student1.setName("Alice");
    student1.setAge(20);
    student1.setStudentID(12345);

    student1.displayStudent();

    return 0;
}

Output

Name: Alice, Age: 20
Student ID: 12345

Explanation

  • The name and age attributes are declared as protected.
  • They can be accessed and modified in the derived class Student through inherited public methods.

Example Programs

Example 1: BankAccount Class with Different Access Specifiers

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;

public:
    string accountHolder;

    BankAccount(string name, double initialBalance) {
        accountHolder = name;
        balance = initialBalance;
    }

    void deposit(double amount) {
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
        } else {
            cout << "Insufficient balance!" << endl;
        }
    }

    void displayBalance() {
        cout << "Account Holder: " << accountHolder << ", Balance: $" << balance << endl;
    }
};

int main() {
    BankAccount account1("John Doe", 1000.0);

    account1.deposit(500.0);
    account1.withdraw(200.0);
    account1.displayBalance();

    account1.withdraw(1500.0);
    account1.displayBalance();

    return 0;
}

Output

Account Holder: John Doe, Balance: $1300
Insufficient balance!
Account Holder: John Doe, Balance: $1300

Explanation

  • The balance attribute is private and can only be accessed and modified through public methods deposit, withdraw, and displayBalance.
  • The accountHolder attribute is public and can be accessed directly.

Example 2: Employee Class with Protected Access Specifier

#include <iostream>
using namespace std;

class Employee {
protected:
    string name;
    int id;

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

    void setID(int i) {
        id = i;
    }

    void display() {
        cout << "Name: " << name << ", ID: " << id << endl;
    }
};

class Manager : public Employee {
public:
    string department;

    void setDepartment(string d) {
        department = d;
    }

    void displayManager() {
        display();
        cout << "Department: " << department << endl;
    }
};

int main() {
    Manager mgr;
    mgr.setName("Alice");
    mgr.setID(101);
    mgr.setDepartment("HR");

    mgr.displayManager();

    return 0;
}

Output

Name: Alice, ID: 101
Department: HR

Explanation

  • The name and id attributes are protected and can be accessed in the derived class Manager.
  • The department attribute is specific to the Manager class.

Summary

  • Public Access Specifier: Members are accessible from outside the class. They are generally used for methods that provide an interface to the class.
  • Private Access Specifier: Members are accessible only within the class. They are used to encapsulate the internal state of the object and protect it from unintended interference.
  • Protected Access Specifier: Members are accessible within the class and its derived classes. They provide a way to allow derived classes to access certain members of the base class while keeping them hidden from the outside world.

Understanding and using access specifiers correctly is crucial for implementing encapsulation in C++ and creating robust, maintainable code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top