C++ Access Specifiers


In object-oriented programming, data protection is a key concept. You don’t always want every part of your program to directly access or modify your class data. This is where access specifiers come into play.

Access specifiers in C++ define the scope and visibility of class members (variables and functions). They control how the members of a class can be accessed from outside the class or within derived classes.

What Are Access Specifiers?

Access specifiers are keywords used to set the access level of class members.
There are three main access specifiers in C++:

  1. Public

  2. Private

  3. Protected

Each one defines a different level of accessibility for class members.

1. Public Access Specifier

Members declared under the public keyword are accessible from anywhere — both inside and outside the class.

You usually make member functions public so that they can be called by objects to perform operations.

Example:

#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int age;

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

int main() {
    Student s1;
    s1.name = "Priya";
    s1.age = 20;
    s1.display();  // Accessible because display() is public
    return 0;
}

Output:

Name: Priya, Age: 20

Here, name, age, and display() are public, so they can be accessed directly through the object s1.

2. Private Access Specifier

Members declared under the private keyword are not accessible from outside the class. They can only be accessed by member functions or friend functions of the class.

Private members are typically used to protect data from direct modification. This is an essential part of encapsulation.

Example:

#include <iostream>
using namespace std;

class Employee {
private:
    int salary;

public:
    void setSalary(int s) {
        salary = s;
    }

    void showSalary() {
        cout << "Salary: " << salary << endl;
    }
};

int main() {
    Employee e1;
    // e1.salary = 50000;  // ❌ Error: salary is private
    e1.setSalary(50000);
    e1.showSalary();
    return 0;
}

Output:

Salary: 50000

In this example, the salary variable is private, so it cannot be accessed directly. Instead, we use the public method setSalary() to modify it.

3. Protected Access Specifier

Members declared as protected are similar to private members, but they can also be accessed by derived (child) classes.

Protected members are not accessible by objects, but they are inherited by subclasses.

Example:

#include <iostream>
using namespace std;

class Person {
protected:
    string name;
};

class Student : public Person {
public:
    void setName(string n) {
        name = n;  // Accessible here because it’s protected
    }

    void showName() {
        cout << "Name: " << name << endl;
    }
};

int main() {
    Student s1;
    s1.setName("Meena");
    s1.showName();
    return 0;
}

Output:

Name: Meena

Here, name is declared as protected in the base class Person. It’s not accessible directly from the object but can be accessed inside the derived class.

Default Access Level in Classes

If you don’t specify any access specifier, members of a class are private by default.

Example:

#include <iostream>
using namespace std;

class Student {
    string name;  // Default: private

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

    void showName() {
        cout << "Name: " << name << endl;
    }
};

int main() {
    Student s1;
    // s1.name = "Riya";  // ❌ Error: name is private
    s1.setName("Riya");
    s1.showName();
    return 0;
}

If you want the members to be publicly accessible, you must explicitly declare them under public:.

Access Specifiers and Inheritance

When you use inheritance, the access level of inherited members can change based on how the base class is inherited (public, protected, or private).

Here’s a quick summary:

Inheritance Type Public Members Become Protected Members Become Private Members Become
Public Public Protected Not Inherited
Protected Protected Protected Not Inherited
Private Private Private Not Inherited

Example:

#include <iostream>
using namespace std;

class Base {
public:
    int a;
protected:
    int b;
private:
    int c;
};

class Derived : public Base {
public:
    void showAccess() {
        a = 10;  // ✅ public member accessible
        b = 20;  // ✅ protected member accessible
        // c = 30;  // ❌ private member not accessible
    }
};

int main() {
    Derived d;
    d.a = 100;  // ✅ public member accessible
    // d.b = 200;  // ❌ protected member not accessible
    // d.c = 300;  // ❌ private member not accessible
    return 0;
}

This example shows how each access level behaves when inherited.

Why Are Access Specifiers Important?

Access specifiers are not just about controlling visibility. They play a big role in object-oriented principles:

  • Encapsulation: Protects internal data from direct modification.

  • Data Security: Prevents accidental or unauthorized access.

  • Code Maintenance: Makes the class easier to update without breaking other parts of the program.

  • Abstraction: Hides unnecessary implementation details from the user.

Real-Life Example

Let’s take a simple real-world example to understand their purpose.

#include <iostream>
using namespace std;

class BankAccount {
private:
    double balance;

public:
    BankAccount(double initialBalance) {
        balance = initialBalance;
    }

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

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) balance -= amount;
    }

    void showBalance() {
        cout << "Current Balance: " << balance << endl;
    }
};

int main() {
    BankAccount account(1000);
    account.deposit(500);
    account.withdraw(200);
    account.showBalance();

    // account.balance = 99999;  // ❌ Not allowed: balance is private
    return 0;
}

Output:

Current Balance: 1300

Here, the balance is private, ensuring that only controlled access is allowed through public functions.

Key Points to Remember

  • public members can be accessed from anywhere.

  • private members can be accessed only inside the class.

  • protected members can be accessed inside the class and by derived classes.

  • If no specifier is mentioned, class members are private by default.

  • Access specifiers are crucial for data protection and encapsulation.

Summary of the Tutorial

In this tutorial, you learned about C++ Access Specifiers — public, private, and protected — and how they define the visibility of class members.
You also saw how access specifiers behave with inheritance, and why they are important for security, encapsulation, and clean program design.

Understanding access specifiers helps you write well-structured, safe, and maintainable object-oriented code in C++.


Practice Questions

  1. Write a C++ program to create a class Student with public data members for name and roll number. Display the details using an object.

  2. Create a class Employee with a private member salary and public methods to set and get the salary. Prevent direct access to the salary variable.

  3. Define a class BankAccount where balance is private and can only be modified using deposit() and withdraw() functions.

  4. Write a program to demonstrate the use of the protected access specifier by creating a base class Person and a derived class Teacher.

  5. Create a class Car with private data members brand and model, and public functions to set and display these values.

  6. Define a class Book that has both public and private members. Show how to access public members directly and private ones through methods.

  7. Write a program that demonstrates how private data members of a class cannot be accessed directly from main().

  8. Create a base class Vehicle with protected members and derive a class Bus that accesses those protected members inside its member function.

  9. Define a class Account without specifying any access specifier for its members. Check whether they are accessible directly from the main function.

  10. Write a C++ program showing how the visibility of public, protected, and private members changes in inheritance when using public, protected, and private modes.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top